package com.homwee.factory;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.bluetooth.BluetoothDevice;
import android.graphics.Color;
import android.os.Looper;
import android.os.PowerManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Instrumentation;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.tv.TvInputInfo;
import android.media.tv.TvInputManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.SystemProperties;
import android.os.Build;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import static android.provider.Settings.System.SCREEN_OFF_TIMEOUT;
import android.text.format.DateUtils;

import android.view.InputDevice;
import android.os.Message;

import com.homwee.factory.util.BTManager;
import com.homwee.factory.util.Contants;
import com.homwee.factory.util.view.FactoryKeyResultDialog;
import com.homwee.tvap.common.ap.ComSettingManager;
import com.homwee.tvap.common.srvfunc.FactorySetting;
import com.mediatek.twoworlds.factory.MtkTvFApiInformation;
import com.mediatek.twoworlds.factory.MtkTvFApiSystem;
import com.mediatek.twoworlds.factory.common.MtkTvFApiSystemTypes;
import com.mediatek.twoworlds.tv.MtkTvCI;
import com.mediatek.twoworlds.tv.MtkTvConfig;
import com.mediatek.twoworlds.tv.MtkTvInputSource;
import com.mediatek.twoworlds.tv.common.MtkTvConfigType;
import com.mediatek.twoworlds.tv.common.MtkTvConfigTypeBase;
import com.mediatek.twoworlds.tv.MtkTvBroadcast;
import android.net.wifi.WifiManager;
import android.net.wifi.ScanResult;
import android.bluetooth.BluetoothAdapter;
import com.mediatek.twoworlds.factory.common.MtkTvFApiResultTypeBase;
import android.content.pm.PackageManager;
import android.content.pm.IPackageDataObserver;
import android.content.SharedPreferences;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.mediatek.twoworlds.factory.clientwrapper.MtkTvFApiInformationWrapper;
import com.mediatek.twoworlds.factory.common.MtkTvFApiPeripheralTypes.IicDevice;
import com.mediatek.twoworlds.factory.model.MtkTvFApiIicReadMode;
import com.mediatek.twoworlds.factory.MtkTvFApiPeripheral;
import com.mediatek.twoworlds.tv.model.MtkTvChannelInfoBase;
import com.mediatek.twoworlds.tv.MtkTvMultiView;
import android.hardware.input.InputManager;
import com.mediatek.wwtv.tvcenter.util.SaveValue;
import com.mediatek.twoworlds.tv.MtkTvUtil;
import com.mediatek.twoworlds.tv.common.MtkTvIntentBase;
import com.mediatek.wwtv.tvcenter.util.MarketRegionInfo;
//gzx 2023-4-17 BS\CS power
import cn.com.dragontec.livetv_aidl.LiveTVUtil;


//zcj 2018-10-31 import android.os.storage.StorageVolume;

public class FactoryKeyReciver extends BroadcastReceiver {
    private static final String TAG = "CHFactory.FactoryKeyReciver";
    public static int FILE_EXPLORER_TYPE_IMAGE = 3;
    public static int FILE_EXPLORER_TYPE_MUSIC = 2;
    public static int FILE_EXPLORER_TYPE_VIDEO = 1;
    public static int FILE_EXPLORER_TYPE_ALL = 0;

    public static final int USB_CHECK = 0;
    public static final int LAN_CHECK = 1;
    public static final int WIFI_CHECK = 2;
    public static final int BT_CHECK = 3;
    public static final int KEY_STATUS_CHECK = 4;
    public static final int EEPROM_STATUS_SHOW=5;
    static boolean isServiceWorked = false;
    public static final String mBrand = android.os.Build.BRAND;
    //public static final String mProduct = ProductFun.getProduct();
    public static final String mProduct = SystemProperties.get("ro.product.name", "");
    public static final String productName=SystemProperties.get("ro.product.name", "");


    public Context mContext = null;// FactoryActivity.mContext;

    public static Toast mToast = null;
    public static FactoryToast mMyToast = null;
    public static String sourceStr = null;
    public int mKeyCode = -1;
    public int mAction = -1;
    FactoryKeyResultDialog mFactoryKeyResultDialog = null;

    private static final String ACTION_GLOBAL_BUTTON = "android.intent.action.GLOBAL_BUTTON";
    private static final String ACTION_BOOT_COMPLETED = "android.intent.action.BOOT_COMPLETED";
    public static final String ACTION_TV_INPUT_BUTTON = "com.mstar.android.intent.action.TV_INPUT_BUTTON";
    public static final String ACTION_SCREEN_OFF = "android.intent.action.SCREEN_OFF";
    private final String PREFERENCES_TV_REMOTE_CLEAR = "tv-remote-service-clear";
    private final String PREFERENCES_WIFI_MAC_ADDRESS = "tv-wifimac-address";
    // public static MiscManager mMiscManager;
    // public static PictureManager mPictureManager;
    public static String readMACString="ff:ff:ff:ff:ff:ff";
    public static String readDeviceString="";
    public static String readPid="00";
    private int halfHour =30*60*1000;
    String autoBoot;
	private BTManager mBtManager;
    private BluetoothAdapter mBluetoothAdapter;


    ArrayList<MtkTvInputSource.InputSourceRecord> inputList = new ArrayList<MtkTvInputSource.InputSourceRecord>();
    ArrayList<String> mUiSourceList = new ArrayList<String>();
    ArrayList<String> mUiSourceListInputName = new ArrayList<String>();
    Map<String, String> sourceMap = new HashMap<String, String>();
    final File[] mKeyDirs = new File[Contants.mKeyPathStrings.length];
    final Boolean[] mKeyDirExistsBooleans = new Boolean[Contants.mKeyPathStrings.length];
    final Boolean[] mKeyFileExistsBooleans = new Boolean[Contants.mKeyPathStrings.length];
    final Boolean[] mKeyFileUpdatesBooleans = new Boolean[Contants.mKeyPathStrings.length];
    final Boolean[] mKeyFileTvExistBooleans = new Boolean[Contants.mKeyPathStrings.length];
    private final int MESSAGE_UPDATE_STATE = 0x1000;
    private final int MESSAGE_UPDATE_KEY = 0x1001;
    private final int COLOR_RED = android.graphics.Color.RED;
    private final int COLOR_GREEN = android.graphics.Color.GREEN;
    private final int COLOR_WHITE = android.graphics.Color.WHITE;
    private int updateKeyRet =-1;

    public Map<String,Object> mDataIndex;

    private String KEY_EEPROM_PATH = "/vendor/cusdata/factory/eeprom/eeprom_key_setting_cus.ini";
    public static final int REGION_CN       = 0;
    public static final int REGION_US       = 1;
    public static final int REGION_SA       = 2;
    public static final int REGION_EU       = 3;
    public static final int REGION_JP       = 4;

    //BS_CS
    private static boolean isLiveTVConnected = false;
    private static LiveTVUtil bscsliveTvUtil =new LiveTVUtil();
    private static LiveTVUtil.ILiveTVUtilCallback liveTVUtilCallback = new LiveTVUtil.ILiveTVUtilCallback(){

        @Override
        public void onServiceConnectionChanged(boolean isConnected) {
            //aidl 
            checkLiveTVConnection();
            Log.d(TAG, "isLiveTVConnected1"+isLiveTVConnected);
        }

        @Override
        public void onLiveTVInited() {
            //aidl 
            checkLiveTVConnection();
            Log.d(TAG, "isLiveTVConnected2"+isLiveTVConnected);
        }
    };

    private static void checkLiveTVConnection(){
        isLiveTVConnected = bscsliveTvUtil.isServiceConnected() && bscsliveTvUtil.isInited();
        Log.d(TAG, "isLiveTVConnected3"+bscsliveTvUtil.isServiceConnected() +" "+bscsliveTvUtil.isInited());
    }

    public static enum EnumEepromKey {
        E_EepromKey_HDCP14,
        E_EepromKey_HDCP2,
        E_EepromKey_MAC,
        E_EepromKey_WIDEVINE,
        E_EepromKey_PLAYREADY30_BGROUPCERT,
        E_EepromKey_PLAYREADY30_ZGPRIV,
        //    E_EepromKey_KEYMASTER,
        E_EepromKey_NETFLIX50_KPEKPH,
        E_EepromKey_NETFLIX50_ESNID,
        E_EepromKey_HASHKEY,
        E_EepromKey_PROJECT_ID,
        E_EepromKey_DEVICE_ID,
        E_EepromKey_MMODE,
        E_EepromKey_AGINGMODE,
        E_EepromKey_CIPLUS,
    }

    private Runnable mRunForSetAntenna = new Runnable() {

        @Override
        public void run() {
            String dvbsEnable = MtkTvFApiInformation.getInstance().getIniParameter(
                Contants.PATH_CUSTOM_FUNC_INI, Contants.FACTORY_DVB_SCAN_S);
            // TODO Auto-generated method stub
            int curAntMode = MtkTvConfig.getInstance().getConfigValue(
                    MtkTvConfigType.CFG_BS_BS_SRC);
            int antType = dvbsEnable.equals("0")? 2 :3;
            if(mProduct.contains("ATSC")||mProduct.contains("ISDB")){
                antType=2;
            }
            Log.d(TAG, "curAntMode:" + curAntMode + " antType "+antType);

            switch ((curAntMode + 1) % antType) {
                case 0: {
                    showToast("AIR");
                    MtkTvConfig.getInstance().setConfigValue(
                            MtkTvConfigType.CFG_BS_BS_SRC, MtkTvConfigTypeBase.ACFG_BS_SRC_AIR);
                    MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff,0);
                    channelInfo.setChannelId(0xffffffff);
                    MtkTvBroadcast.getInstance().channelSelect(channelInfo,false);
                    break;
                }
                case 1: {
                    showToast("CABLE");
                    MtkTvConfig.getInstance().setConfigValue(
                            MtkTvConfigType.CFG_BS_BS_SRC, MtkTvConfigTypeBase.ACFG_BS_SRC_CABLE);
                    MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff,0);
                    channelInfo.setChannelId(0xffffffff);
                    MtkTvBroadcast.getInstance().channelSelect(channelInfo,false);
                    break;
                }
                case 2: {
                    showToast("Satellite");
                    MtkTvConfig.getInstance().setConfigValue(
                            MtkTvConfigType.CFG_BS_BS_SRC, 3);//MtkTvConfigTypeBase.ACFG_BS_SRC_SAT); //3 is set to general SAT
                    MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff, 0);
                    channelInfo.setChannelId(0xffffffff);
                    MtkTvBroadcast.getInstance().channelSelect(channelInfo, false);
                    break;
                }
                default:
                    break;
            }
        }

    };
    final Handler mHandler = new Handler(){
	    @Override
	    public void handleMessage(Message msg){
		    super.handleMessage(msg);
		    if(msg.what == MESSAGE_UPDATE_STATE){
		        Log.v(TAG,"handlemessage STATE");
                        String keyret = msg.getData().getString("keyret");
                        if("SOURCE".equals(keyret)){
                             String sourcename = MtkTvInputSource.getInstance().getCurrentInputSourceName(); 
                             int color = msg.getData().getInt("color"); 
                             if(MtkTvBroadcast.getInstance().isSignalLoss()){
                                color = COLOR_RED;
                             } else { 
                                color = COLOR_GREEN;
                             }
                             updateStateService((Context)msg.obj, 0,sourcename, color);
                        }
//                        updateStateService((Context)msg.obj, 0,msg.getData().getString("text"), msg.getData().getInt("color"));
		    } else if(msg.what == MESSAGE_UPDATE_KEY){
                        String keyret = msg.getData().getString("keyret");
                        if("ANT".equals(keyret)){
                        updateStateService((Context)msg.obj, 1,getCurrentAnt(), msg.getData().getInt("color"));
                        } else {
                        updateStateService((Context)msg.obj, 1,msg.getData().getString("text"), msg.getData().getInt("color"));
                        }
                    }
	    }
    };

    Handler btHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case BTManager.MSG_BT_DEVICE_FOUND:
                    BluetoothDevice device = (BluetoothDevice) msg.obj;
                    if (device == null || device.getName() == null) {
                        break;
                    }

                    if (!device.getName().equalsIgnoreCase("null")
                    ) {
                        if (!mBtManager.BTData.contains(device.getName())){
                            mBtManager.BTData.add(device.getName());
                        }
                    }
                    if (mBtManager.BTData.size() >= 3) {
                        mBluetoothAdapter.cancelDiscovery();
                    }

                    break;
                default:
                    break;
            }
        }
    };

    @SuppressWarnings("deprecation")
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        ComSettingManager mcomSettingManager = ComSettingManager
                .getInstance(context);
        final FactorySetting factorySetting = mcomSettingManager.getFactory();
        mKeyCode = -1;
        mAction = -1;

        final Context mContext = context;
        final String action = intent.getAction();
        Log.d(TAG, "action = " + action + "  context = " + context);

        init(context,factorySetting);

        bscsliveTvUtil.removeCallback(liveTVUtilCallback);
        bscsliveTvUtil.addCallback(liveTVUtilCallback);
        bscsliveTvUtil.setContext(context.getApplicationContext());


        //FactoryDataIndexInit dataInit = FactoryDataIndexInit.getInstance(factorySetting.getDataIndex());
        if (TextUtils.isEmpty(Contants.FACTORY_EXTRA_BOARD_PATH)) {
            initDataPath(context,factorySetting);
            Log.d(TAG,"init done");
        }
        if (Intent.ACTION_SHUTDOWN.equals(action)
                || Intent.ACTION_SCREEN_OFF.equals(action)) {
            try {
                setFactoryMMode(context, 0);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        if (ACTION_GLOBAL_BUTTON.equals(action)) {
            KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
            {
                mKeyCode = event.getKeyCode();
            }
            mAction = event.getAction();
            Log.d(TAG, "mKeyCode:" + mKeyCode + " ;mAction:" + mAction);
			Log.d(TAG, "event.getScanCode() = " + event.getScanCode());
			InputDevice myDevice = InputDevice.getDevice(event.getDeviceId());
			
			if(mKeyCode==KeyEvent.KEYCODE_BUTTON_13&&myDevice.getName().equals("MTK TV KEYPAD")&&116==event.getScanCode()){
				Log.d(TAG, " getRepeatCount = " + event.getRepeatCount());
				if(event.getRepeatCount()>5&&mAction==KeyEvent.ACTION_DOWN){
					Log.d(TAG, "shutdown");
					PowerManager pManager = (PowerManager) mContext.getSystemService(mContext.POWER_SERVICE); 
					pManager.shutdown(false,PowerManager.SHUTDOWN_USER_REQUESTED,false);
				}
				else if(mAction==KeyEvent.ACTION_UP){
					sendKeyCode();
					Log.d(TAG, "sendKeyCode");
				}
			}

        }

        if (ACTION_BOOT_COMPLETED.equals(action)) {

            /** Burn key when boot on */
            //int updateKeyRet =-1;
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    for (int i = 0; i < 6; i++) {
                        try {
                            Log.d(TAG, "=====Boot on Burn Key :" + i + " =====");
                            if (isFirstUpdateKey(factorySetting)) {
                                updateKeyRet = updateAllKeys(context, factorySetting, mContext, true);
                            }
                            if (updateKeyRet == 0) {
                                break;
                            } else {
                                Thread.sleep(10 * 1000);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }.start();

//      emmc preset channel list,remove boot complete preset channel
//           if(factorySetting.getRemoteChannelPreset()!=0) {
//                if (isChannelDirExists(factorySetting)) {
//                    loadChannelList(context, factorySetting);
//                }
//			}
			
			if(isAutoTestStart()){
            	Intent intentAutoTestRetShow = new Intent();
				intentAutoTestRetShow.setClassName("com.homwee.factory","com.homwee.factory.CHFactoryCheckActivity");
                mContext.startActivity(intentAutoTestRetShow);
			}

			presetHashkey();
            
            if (factorySetting.getAgingModel() == 1||isFactoryMMode(context)) {
                if(!isFactoryMMode(context) && !mBrand.equals("Philco")) {
                    setFactoryMMode(context, 1);
                }

				BTCheck(context.getApplicationContext());
				Log.d(TAG,"start BT check");
				getDeviceMac(context.getApplicationContext());

                int picMode=Settings.Global.getInt(context.getContentResolver(), "picture_mode",0);
                Settings.Global.putInt(context.getContentResolver(), getBlackLightName(picMode),0);
				
            	Intent intentForBarServer = new Intent(mContext,FactoryModeService.class);
                mContext.startService(intentForBarServer);
            }

            //AutoEnterFactory
            if(factorySetting.getAutoEnterFactory().equals("1")){
                ((Activity) FactoryActivity.mContext).finish();
                //switch to HDMI1
                changeSourceByBroadcast(context, "HDMI 1",-1);
                //perset Channel list
                int needPersetChannel=Settings.Global.getInt(context.getContentResolver(),"FactoryChannelSet",0);
                if(needPersetChannel==0) {
                    mContext.sendBroadcast(new Intent(MtkTvIntentBase.MTK_INTENT_EVENT_PRESET_CHANNEL_LOAD_START));
                    if (MtkTvFApiSystem.getInstance().isFileExist("/vendor/tvcertificate/Channel_list")) {
                        int ret = MtkTvConfig.getInstance().loadChannelListByPath(1, "/vendor/tvcertificate/channel_list");
                        Log.v("tv", "loadchannellist ret" + ret);
                    } else {
                        int ret = MtkTvConfig.getInstance().loadChannelListByPath(1, "/vendor/tvconfig/apollo/channel_list");
                        Log.v("tv", "loadchannellist ret" + ret);
                    }
                    mContext.sendBroadcast(new Intent(MtkTvIntentBase.MTK_INTENT_EVENT_PRESET_CHANNEL_LOAD_END));
                    MtkTvChannelInfoBase channelinfo = new MtkTvChannelInfoBase(0xffff, 0);
                    channelinfo.setChannelId(0xffffffff);
                    MtkTvBroadcast.getInstance().channelSelect(channelinfo, false);
                    Settings.Global.putInt(context.getContentResolver(), "FactoryChannelSet", 1);
                }
                //sound set 85
                factorySetting.setVolume(85);
                //set no signal power off -> off
                Settings.Global.putInt( mContext.getContentResolver(), "no_signal_auto_power_off", 0);
                //disable network policy
                SaveValue.saveWorldBooleanValue(mContext, "network_privacy_policy_enabled", true, true);
                SaveValue.saveWorldBooleanValue(mContext, "network_privacy_policy_decline", false, false);

            }

            if (mBrand.equals("Philco")) {
                if (factorySetting.getAgingModel() == 1) {
                    MtkTvUtil.IRRemoteControl(4);
                    Log.d("zcj", "  start exit key activity");
                    Intent exitActivity = new Intent(mContext, ExitKeyReceiveActivity.class);
                    exitActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(exitActivity);
                }
                if (factorySetting.getIsFirstPowerON() == 1) {
                    factorySetting.setPowerMode(0);
                    factorySetting.setFirstPowerON(0);
                }
            }

            if(factorySetting.getShowModePlay().equals("1")){
                factorySetting.playDemoVideo(Contants.DEMOVIDEO_PATH,mContext);
            }
            
            if (factorySetting.getKeyStatusIniFileExist()) {
            	if (checkMacAndDeviceID(factorySetting)) {
            		Log.d(TAG, "checkMacAndDeviceID is OK");
				} else {
					 Log.d(TAG, "checkMacAndDeviceID is Not OK");
				}
			}
            Log.d("lhtest00", "action = " + action );
            AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            long triggerAtTime = SystemClock.elapsedRealtime() + halfHour;
            Intent intent2 = new Intent(mContext, FactoryKeyReciver.class);
            intent2.setAction("com.homwee.action.HALF_AN_HOUR_PASS");
            intent2.addFlags(0x01000000);//fix Background execution not allowed
            PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent2, 0);
            manager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, pi);

	    if("m7322".equalsIgnoreCase(SystemProperties.get("ro.board.platform"))&&"Vsmart".equalsIgnoreCase(Build.BRAND)){
			Log.i(TAG,"clearTvRemoteDate --VS");
			SharedPreferences sharedPrefs = context.getSharedPreferences(PREFERENCES_TV_REMOTE_CLEAR, Context.MODE_PRIVATE);
			SharedPreferences.Editor ed;
		    	if(!sharedPrefs.contains("cleared")){
			 Log.i(TAG,"clearTvRemoteDate --VS  cleared false");
				if(MtkTvFApiSystem.getInstance().isFileExist(Contants.PATH_RESETFLAG_INI))
				{
			                Log.i(TAG,"file is exit,do nothing = " +Contants.PATH_RESETFLAG_INI);
				}else{
			                Log.i(TAG,"file is not exit,start to clean");
			                clearTvRemoteDate(mContext);
		             }	
		        ed = sharedPrefs.edit();
		        //Indicate that the default shared prefs have been set
		        ed.putBoolean("cleared", true);
			 String fingerPrint=SystemProperties.get("ro.vendor.build.fingerprint", "");
			 Log.i(TAG,"clearTvRemoteDate --VS  cleared false"+" fingerPrint="+fingerPrint);
			 ed.putString("fingerPrint", fingerPrint);
		        ed.commit();
		    }  
		    else{
				Log.i(TAG,"clearTvRemoteDate --VS  cleared true");
				String fingerPrint=SystemProperties.get("ro.vendor.build.fingerprint", "");
				String value = sharedPrefs.getString("fingerPrint", "");
				Log.i(TAG,"clearTvRemoteDate --VS  cleared true"+" NOW fingerPrint="+fingerPrint);
				Log.i(TAG,"clearTvRemoteDate --VS  cleared true"+" SAVE fingerPrint="+value);
				if(!fingerPrint.equals(value))
				{
					Log.i(TAG,"clearTvRemoteDate --VS  cleared true fingerPrint change");
					if(MtkTvFApiSystem.getInstance().isFileExist(Contants.PATH_RESETFLAG_INI))
					{
					    Log.i(TAG,"file is exit,do nothing = " +Contants.PATH_RESETFLAG_INI);
					}else{
					    Log.i(TAG,"file is not exit,start to clean");
					    clearTvRemoteDate(mContext);
					}	
					ed = sharedPrefs.edit();
					ed.putString("fingerPrint", fingerPrint);
					ed.commit();
				}
				else{
					Log.i(TAG,"clearTvRemoteDate --VS  cleared true fingerPrint not change");
				}
			}
	 	}
        }
        
        if(action.equals("com.homwee.action.HALF_AN_HOUR_PASS")){
        	Log.d("lhtest11", "action = " + action );
        	factorySetting.setTvWorkTime();
        	AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            long triggerAtTime = SystemClock.elapsedRealtime() + halfHour;
            Intent intent2 = new Intent(mContext, FactoryKeyReciver.class);
            intent2.setAction("com.homwee.action.HALF_AN_HOUR_PASS");
            PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent2, 0);
            manager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime, pi);
        }

        if(action.equals("com.homwee.action.FactorySkipWizard")){
            if(!factorySetting.isResetStart()) {
                Log.d(TAG, "Reciver FactorySkipWizard");
                if (mBrand.equals("Philco")) {
                    Log.d(TAG, "Reciver FactorySkipWizard,brand is pl");
                    factorySetting.setPowerMode(2);
                    //set HDMI CEC ON
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_control_enabled", 1);
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_control_auto_device_off_enabled", 1);
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_control_auto_wakeup_enabled", 1);
                } else {
                    FactoryKeyReciver.setFactoryMMode(context, 1);
                    factorySetting.setPowerMode(2);
                    factorySetting.setVolume(85);
                    //DAP OFF
                    Settings.Global.putInt(context.getContentResolver(),
                            "sound_advanced_dolby_ap", 0);
                    /*Intent intentForBarServer = new Intent(
                            "FactoryModeService");
                    intentForBarServer.setPackage("com.homwee.factory");
                    mContext.startService(intentForBarServer);*/
                    Intent intentForBarServer = new Intent(context, FactoryModeService.class);
                    context.startService(intentForBarServer);
                    FactoryModeMenu.refresh(context);
                }
            }
        }
		
		if(action.equals("com.homwee.action.CLEARAPPDATA")){
            if(MtkTvFApiSystem.getInstance().isFileExist(Contants.PATH_RESETFLAG_INI))
            {
                Log.i(TAG,"file is exit,do nothing = " +Contants.PATH_RESETFLAG_INI);
            }else{
                Log.i(TAG,"file is not exit,start to clean");
                clearApplications(mContext);
            }	
		}

        FactoryModeMenu.refresh(context);

        // handle key event
        if (mAction == KeyEvent.ACTION_UP) {

            if (!isFactoryMMode(context)) {
                // aging init client preset factory preset data
                // display search program
                if(!(mBrand.equals("Philco"))) {
                    if (mKeyCode == KeyEvent.KEYCODE_TV_INPUT_VGA_1
                            || mKeyCode == KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
                            || mKeyCode == KeyEvent.KEYCODE_SOFT_RIGHT
                            || mKeyCode == KeyEvent.KEYCODE_SOFT_LEFT
                            || mKeyCode == KeyEvent.KEYCODE_FOCUS
                            || mKeyCode == KeyEvent.KEYCODE_AVR_INPUT
                            || mKeyCode == KeyEvent.KEYCODE_REFRESH
                            || mKeyCode == KeyEvent.KEYCODE_BUTTON_B
                            || mKeyCode == KeyEvent.KEYCODE_NAVIGATE_IN
                            || mKeyCode == KeyEvent.KEYCODE_NAVIGATE_OUT) {
                        Toast.makeText(context, " Please set M Mode at first!",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
            }
            switch (mKeyCode) {
                // F14 initialization
                case KeyEvent.KEYCODE_SOFT_LEFT: {
                            // TODO Auto-generated method stub
//                            Toast.makeText(mContext,
//                                    mContext.getString(R.string.factory_clean_data_wait),
//                                    Toast.LENGTH_SHORT).show();
//                            // toast.setGravity(mPaddingRight, 0, 0);
//                            Timer timer = new Timer();
//                            TimerTask task = new TimerTask() {
//                                public void run() {
//                                    factorySetting.cleanApp(false);
//                                }
//                            };
//                            timer.schedule(task, 300);
//                    Log.v("tv", "systemInit");
//                    FactoryDialog mDialog = new FactoryDialog(mContext,"FACTORY_RESET");
//                    mDialog.getWindow().setType(
//                            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                    mDialog.show();

                    //quickReset here
                    if(isAllKeyExist(factorySetting)){
                        //change source to TV
                        if(mProduct.contains("DVB")){
                            changeSourceByBroadcast(context,"DTV",0);
                        }else {
                            changeSourceByBroadcast(context, "TV",-1);
                        }
                        //factorySetting.resetAutoEnterFactoryIni();
                        MtkTvUtil.IRRemoteControl(1);
                        factorySetting.factoryResetPowerMode();
                        factorySetting.quickSystemInit();
                    }else{
                        showToast("Key(s) is missing,can't restore the factory settings");
                    }
                }

                break;
                // F8 aging mode
                case KeyEvent.KEYCODE_SOFT_RIGHT: {
                	//remove for aging mode switch to launcher issue.
					//autoBoot=MtkTvFApiInformation.getInstance().getIniParameter(
            		//	Contants.PATH_CUSTOM_FUNC_INI, Contants.FACTORY_BOOT_TYPE);
					//if(autoBoot.equals("0")){
					//	Intent i= new Intent(Intent.ACTION_MAIN);
               		//	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      		 		//	i.addCategory(Intent.CATEGORY_HOME);
					//	context.startActivity(i);
               		//	}
					//aging mode set picture mode		
                	Settings.Global.putInt(context.getContentResolver(), "picture_mode", 0);
                	Settings.Global.putInt(context.getContentResolver(), "picture_backlight", 100);

                    if (factorySetting.getAgingModel() == 1) {
                        factorySetting.setAgingModel(0);
                        Intent intentForBarCode = new Intent();
                        intentForBarCode
                                .setAction("com.homwee.action.STOP_FACTORY_SERVICE");
                        //mContext.sendBroadcast(intentForBarCode);

                        if (mBrand.equals("Philco")) {
                            ActivityManager mActivityManager = (ActivityManager) context
                                    .getSystemService(Context.ACTIVITY_SERVICE);
                            List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                                    .getRunningTasks(100);
                            for (ActivityManager.RunningTaskInfo running : appList) {
                                Log.v("tv",
                                        "factory1 =" + running.baseActivity.getClassName());
                                if ("com.homwee.factory.ExitKeyReceiveActivity"
                                        .equals(running.topActivity.getClassName())) {
                                    long now = SystemClock.uptimeMillis();
                                    KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, 4, 0);
                                    InputManager.getInstance().injectInputEvent(down, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
                                    now = SystemClock.uptimeMillis();
                                    KeyEvent up = new KeyEvent(now, now, KeyEvent.ACTION_UP, 4, 0);
                                    InputManager.getInstance().injectInputEvent(up, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
                                    break;
                                }
                            }
                        }

                    } else {
                        factorySetting.setAgingModel(1);
                        /*Intent intentForBarServer = new Intent(
                                "FactoryModeService");
                        intentForBarServer.setPackage("com.homwee.factory");*/
						Intent intentForBarServer = new Intent(mContext,FactoryModeService.class);
                        mContext.startService(intentForBarServer);
                        if (mProduct.contains("ISDB")) {
                            Log.d("zcj", "  start exit key activity");
                            Intent exitActivity = new Intent(mContext, ExitKeyReceiveActivity.class);
                            exitActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            mContext.startActivity(exitActivity);
                        }
                    }
                }

                break;
                // S mode
                case KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP: {

                    if(mProduct.contains("ISDB")){
                        if(mBrand.equals("Philco")){
                            if (!getMacBarShow(context)) {
                                Log.d(TAG, "cyf test F4 start show");
                                setMacBarShow(context, 1);
                                Intent intentForBarServer = new Intent(
                                        "com.homwee.macbarcode.BarCodeService");
                                intentForBarServer.setPackage("com.homwee.factory");
                                intentForBarServer.putExtra("showItem", "ESN");
                                mContext.startService(intentForBarServer);
                            } else {
                                Log.d(TAG, "cyf test F4 stop show");
                                setMacBarShow(context, 0);
                                Intent intentForBarCode = new Intent();
                                intentForBarCode
                                        .setAction("com.homwee.macbarcode.stopservice");
                                mContext.sendBroadcast(intentForBarCode);
                            }
                        }
                    }

                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        Log.v("tv",
                                "factory2 =" + running.topActivity.getClassName());
                        if ("com.homwee.factory.FactoryActivity"
                                .equals(running.topActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }
                    if (!factoryActive) {
                        Log.v("tv", "ss");
                        Intent myIntent = new Intent();
                        myIntent.setComponent(new ComponentName(
                                "com.homwee.factory",
                                "com.homwee.factory.FactoryActivity"));
                        myIntent.addFlags(myIntent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(myIntent);
 
                        updateStateService(mContext, 1, "S", COLOR_WHITE);
                    } else {
                        Log.v("tv", "s kill");
                        ((Activity) FactoryActivity.mContext).finish();
 
                        updateStateService(mContext, 1, "", COLOR_WHITE);
                    }

                    FactoryModeMenu.refresh(context);
                }

                break;
                // M mode
                case KeyEvent.KEYCODE_AT: {
                    if (isFactoryMMode(context)) {
                        setFactoryMMode(context, 0);
                        //factorySetting.setPowerMode(0);
                        factorySetting.factoryResetPowerMode();
                        Intent intentForBarCode = new Intent();
                        intentForBarCode
                                .setAction("com.homwee.action.STOP_FACTORY_SERVICE");
                        mContext.sendBroadcast(intentForBarCode);
                    } else {
                        setFactoryMMode(context, 1);
                        factorySetting.setPowerMode(2);
                        /*Intent intentForBarServer = new Intent(
                                "FactoryModeService");
                        intentForBarServer.setPackage("com.homwee.factory");
                        mContext.startService(intentForBarServer);*/
						Intent intentForBarServer = new Intent(mContext,FactoryModeService.class);
                        mContext.startService(intentForBarServer);
                    }

                    FactoryModeMenu.refresh(context);
                }

                break;
                // Factory Reset
                case KeyEvent.KEYCODE_TV_INPUT_VGA_1: {
                    Log.v(TAG, "Factory Reset");
//                    FactoryDialog mDialog = new FactoryDialog(mContext,"FACTORY_RESET");
//                    mDialog.getWindow().setType(
//                            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                    mDialog.show();
                    if(isAllKeyExist(factorySetting)){
                        //change source to TV
                        //changeSourceByBroadcast(context,"TV");
                        //factorySetting.resetAutoEnterFactoryIni();
                        factorySetting.systemInit();
                    }else{
                        showToast("Key(s) is missing,can't restore the factory settings");
                    }
                }

                break;
                // factory VOL+
                case KeyEvent.KEYCODE_BUTTON_11: {
                    int vol = factorySetting.getVolume();
                    if ((vol + 15) >= 100) {
                        factorySetting.setVolume(100);
                        updateStateService(mContext, 1, "100", COLOR_WHITE);
                        showToast("100");
                    } else {
                        factorySetting.setVolume(vol + 15);
                        updateStateService(mContext, 1, (vol+15)+"", COLOR_WHITE);
                        showToast("" + (vol + 15));
                    }

                }
                break;
                // factory VOL-
                case KeyEvent.KEYCODE_BUTTON_12: {
                    int vol = factorySetting.getVolume();
                    if ((vol - 15) <= 0) {
                        factorySetting.setVolume(0);
                        updateStateService(mContext, 1, "0", COLOR_WHITE);
                        showToast("0");
                    } else {
                        factorySetting.setVolume(vol - 15);
                        updateStateService(mContext, 1, (vol - 15)+"", COLOR_WHITE);
                        showToast("" + (vol - 15));
                    }
                }
                break;
                // Program Clone
                case KeyEvent.KEYCODE_PICTSYMBOLS: {

                    if (mProduct.contains("ISDB") && mBrand.equals("Philco")) {
                        if (factorySetting.findUsbDir()) {
                            factorySetting.dumpFactoryChannelListByPath(1, Contants.FACTORY_CHANNEL_LIST_PATH_TV);
                            showToast(mContext
                                    .getString(R.string.factory_pageall_success));
                        } else {
                            showToast(mContext
                                    .getString(R.string.factory_reciver_no_usb));
                        }
                    } else {
                        factorySetting.customerUpdate(mContext);
                    }

                    if(factorySetting.isForcePID()){
                        File pidFile=factorySetting.getFile(Contants.FACTORY_FORCE_PROJECT_ID);
                        String pid=MtkTvFApiInformation.getInstance().getIniParameter(
                                pidFile.getAbsolutePath(), Contants.FACTORY_PROJECT_ID);
                        Log.d(TAG,"FORCE UPDATE PID TO "+pid);
                        MtkTvFApiInformation.getInstance().setIniParameter(
                                Contants.PATH_FACTORYINI, Contants.FACTORY_PROJECT_ID, pid);

                        factorySetting.WriteProjectIDToEeprom();
                        MtkTvFApiSystem.getInstance().setEmmcEnvVar("db_table","0");
                    }
                }

                break;
                // Search Program
                case KeyEvent.KEYCODE_BUTTON_B: {
                    Intent intentSearch = new Intent();
                    intentSearch
                            .setClassName("com.mediatek.wwtv.tvcenter",
                                    "com.mediatek.wwtv.setting.base.scan.ui.ScanDialogActivity");
                    intentSearch.putExtra("ActionID", "channel_scan");
                    intentSearch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intentSearch);
                }

                break;
                // Factory Program Preset
                case KeyEvent.KEYCODE_FOCUS: {
                    updateStateService(context, 1, "Program preset", COLOR_WHITE);
                    boolean loadret = loadChannelList(context, factorySetting);
                    updateStateService(context, 1, "P preset " + (loadret?"OK": "Fail"), loadret ? COLOR_GREEN:COLOR_RED);
                   // factorySetting.loadFactoryChannelListByPath(1,Contants.FACTORY_CHANNEL_LIST_PATH_TV);
                        if (mProduct.contains("ISDB") && mBrand.equals("Philco")) {
                            if (factorySetting.findUsbDir()) {
                                MtkTvBroadcast.getInstance().channelSelect(7864576, false);
                                setFactoryMMode(context, 0);
                                MtkTvFApiSystem.getInstance().setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT);
                                factorySetting.setAgingModel(1);
                                Intent exitActivity = new Intent(mContext, ExitKeyReceiveActivity.class);
                                exitActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                mContext.startActivity(exitActivity);
                            }
                        } else if (mBrand.equals("PHILCO") && factorySetting.findUsbDir()) {
                            MtkTvBroadcast.getInstance().channelSelect(6816256, false);
                        }
                }
                break;
                // Factory ATV
                case KeyEvent.KEYCODE_SWITCH_CHARSET: {
                    //swith to AIR
                    //showToast("AIR");
                  //  MtkTvConfig.getInstance().setConfigValue(
                  //          MtkTvConfigType.CFG_BS_BS_SRC, MtkTvConfigTypeBase.ACFG_BS_SRC_AIR);
                  //  MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff, 0);
                  //  channelInfo.setChannelId(0xffffffff);
                  //  MtkTvBroadcast.getInstance().channelSelect(channelInfo, false);
                    updateStateService(mContext, 1, context.getString(R.string.factory_reciver_source_tv_air), COLOR_WHITE);


                    Log.d(TAG, "ATV");
                    if (mProduct.contains("DVB")) {
                        MtkTvMultiView.getInstance().setChgSource(true);
                        Log.d(TAG,"need set ChgSource to 1 .");
                        MtkTvConfig.getInstance().setConfigValue(
                                MtkTvConfigType.CFG_BS_BS_SRC, MtkTvConfigTypeBase.ACFG_BS_SRC_AIR);
				        changeSourceByBroadcast(context, "ATV",-1);
				        MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff, 0);
                        channelInfo.setChannelId(0xffffffff);
                        MtkTvBroadcast.getInstance().channelSelect(channelInfo, false);

                    } else if (mProduct.contains("ISDB")) {
                        MtkTvBroadcast.getInstance().channelSelect(1835136, false);
                        changeSourceByBroadcast(context, "TV",-1);
                    } else if (mProduct.contains("ATSC")) {
                        MtkTvBroadcast.getInstance().channelSelect(1835136, false);
                        changeSourceByBroadcast(context, "TV",-1);
                    }


                }
                break;
                // Factory DTV
                case KeyEvent.KEYCODE_CAMERA: {
                    //switch to AIR
                    //showToast("AIR");
                    MtkTvConfig.getInstance().setConfigValue(
                            MtkTvConfigType.CFG_BS_BS_SRC, MtkTvConfigTypeBase.ACFG_BS_SRC_AIR);
                    MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff, 0);
                    channelInfo.setChannelId(0xffffffff);
                    MtkTvBroadcast.getInstance().channelSelect(channelInfo, false);
                    updateStateService(mContext, 1, context.getString(R.string.factory_reciver_source_tv_air), COLOR_WHITE);

                    Log.d(TAG, "DTV");
                    if(mProduct.contains("DVB")) {
                        if(!isCurSourceIsDtv()){
                            MtkTvMultiView.getInstance().setChgSource(true);
                            Log.d(TAG,"need set ChgSource to 1 .");
                        }
                        if(factorySetting.isColRegion() && getCurrentAnt().equalsIgnoreCase("CABLE")){
                            showToast("is COL Region,no cable DTV,pls set AIR first");
                        }else {
                            changeSourceByBroadcast(context, "DTV", 0);
                        }
                    }else if(mProduct.contains("ISDB")){
                        MtkTvBroadcast.getInstance().channelSelect(2359552, false);
						changeSourceByBroadcast(context, "TV",-1);
                    }else if(mProduct.contains("ATSC")){
						MtkTvBroadcast.getInstance().channelSelect(2621696, false);
                        changeSourceByBroadcast(context, "TV",-1);
                    }
                }
                break;
                // Factory BS/CS POWER
               case KeyEvent.KEYCODE_YEN: {
                   if(REGION_JP == MarketRegionInfo.getCurrentMarketRegion()){
                       boolean isGetLNBSetting=false;
                      // isLiveTVConnected = bscsliveTvUtil.isServiceConnected() && bscsliveTvUtil.isInited();
                       Log.d(TAG, "isLiveTVConnected4"+bscsliveTvUtil.isServiceConnected()+" "+bscsliveTvUtil.isInited());
                       if (!isLiveTVConnected) {
                           showToast("waiting for service init");
                           Log.d(TAG, "isLiveTVConnected5" + isLiveTVConnected);
                       }
                       else{
                           Log.d(TAG, "isLiveTVConnected6"+isLiveTVConnected);
                           isGetLNBSetting= bscsliveTvUtil.getLNBSetting();
                           if(isGetLNBSetting){
                               if(bscsliveTvUtil.setLNBSetting(!isGetLNBSetting)){
                                   showToast("BS_CS Power:OFF");
                               }
                           }else {
                               if(bscsliveTvUtil.setLNBSetting(!isGetLNBSetting)){
                                   showToast("BS_CS Power:ON");
                               }
                           }
                       }
                   }else {
                       showToast("JP use only");
                   }
               }
               break;

                // Factory AV or JP FAC_RECORD_LIST(global)
                case KeyEvent.KEYCODE_DVR: {
                    if (REGION_JP == MarketRegionInfo.getCurrentMarketRegion()){
                        Log.d(TAG,"FactoryKeyReciver_Jp Keycode_DVR_global");
                    }else{
                           changeSourceByBroadcast(context, "Composite",-1);
                    }
                }
                break;
                // Factory AV for JP
                case KeyEvent.KEYCODE_WINDOW: {
                    if (REGION_JP == MarketRegionInfo.getCurrentMarketRegion()){
                            changeSourceByBroadcast(context, "Composite",-1);
                    }else {
                             Log.d(TAG,"FactoryKeyReciver_Keycode_WINDOW");
                    }
                }
                break;
                // Factory USB_UPGRADE
                case KeyEvent.KEYCODE_SLASH: {
                    if(REGION_JP == MarketRegionInfo.getCurrentMarketRegion()){
                          if (mProduct.contains("ISDB") && mBrand.equals("Philco")) {
                        Intent intentSearch = new Intent();
                        intentSearch
                                .setClassName("com.mediatek.wwtv.tvcenter",
                                        "com.mediatek.wwtv.setting.base.scan.ui.ScanViewActivity");
                        intentSearch.putExtra("ActionID", "tv_dvbt_single_rf_scan");
                        intentSearch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intentSearch);
                    } else {
                        boolean factoryActive = false;
                        ActivityManager mActivityManager = (ActivityManager) context
                                .getSystemService(Context.ACTIVITY_SERVICE);
                        List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                                .getRunningTasks(100);
                        for (ActivityManager.RunningTaskInfo running : appList) {
                            Log.v("tv",
                                    "factory1 =" + running.baseActivity.getClassName());
                            if ("com.homwee.factory.FactoryListInfoActivity"
                                    .equals(running.baseActivity.getClassName())) {
                                factoryActive = true;
                                break;
                            }
                        }

                        if (!factoryActive) {
                            Log.v("wql", "keycode=KEYCODE_SLASH-Factory USB_UPGRADE");
                            Intent KsyStatusIntent = new Intent();
                            KsyStatusIntent.setComponent(new ComponentName(
                                    "com.homwee.factory",
                                    "com.homwee.factory.FactoryListInfoActivity"));
                            KsyStatusIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            KsyStatusIntent.putExtra("CheckItem", KEY_STATUS_CHECK);
                            context.startActivity(KsyStatusIntent);
                        } else {
                            Log.v("tv", "s kill");
                            ((Activity) FactoryListInfoActivity.mContext).finish();
                        }
                     }
                    }else{
                           Log.d(TAG,"FactoryKeyReciver_KEYCODE_SLASH");
                    }
                }
                break;
                // Factory YPBPR
                case KeyEvent.KEYCODE_TV_POWER: {
                    //changeSourceByBroadcast(context, "Component");
                    if (productName.contains("96")) {
                        boolean factoryActive = false;
                        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                        List<ActivityManager.RunningTaskInfo> appList = mActivityManager.getRunningTasks(100);
                        for (ActivityManager.RunningTaskInfo running : appList) {
                            Log.v("tv", "factory1 =" + running.baseActivity.getClassName());
                            Log.v("tv", "factory2 =" + running.topActivity.getClassName());
                            if ("com.homwee.factory.FactoryLightSensorActivity".equals(running.topActivity.getClassName())) {
                                factoryActive = true;
                                break;
                            }

                        }

                        if (!factoryActive) {
                            Intent intentForFactoryExtra = new Intent();
                            intentForFactoryExtra.setClass(context, FactoryLightSensorActivity.class);
                            intentForFactoryExtra.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            context.startActivity(intentForFactoryExtra);
                        }else{
                            FactoryLightSensorActivity.instance.finish();
                        }
                    }
                }
                break;
                // Factory USB
                case KeyEvent.KEYCODE_3D_MODE: {
                    //check setupwizard is exist
                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
//                    for (ActivityManager.RunningTaskInfo running : appList) {
//                        Log.v("tv",
//                                "factory1 =" + running.baseActivity.getClassName());
//                        Log.v("tv",
//                                "factory2 =" + running.topActivity.getClassName());
//                        if (running.topActivity.getClassName().contains("com.google.android.tungsten.setupwraith")
//                                ||running.topActivity.getClassName().contains("com.mediatek.wwtv.setupwizard")) {
//                            factoryActive = true;
//                            break;
//                        }
//
//                    }

                    //check 1st activity is enough
                    Log.v("tv",
                            "factory1 =" + appList.get(0).baseActivity.getClassName());
                    Log.v("tv",
                            "factory2 =" + appList.get(0).topActivity.getClassName());
                    if(appList.get(0).topActivity.getClassName().contains("com.google.android.tungsten.setupwraith")
                            ||appList.get(0).topActivity.getClassName().contains("com.mediatek.wwtv.setupwizard")){
                        factoryActive = true;
                    }



                    if(!factoryActive) {
                        boolean USB_OK = false;
                        String path = null;
                        if (factorySetting.findUsbDir()) {
                            File mediaFile = factorySetting.getFile("video.mp4");

                            if (mediaFile.exists()) {
                                path = mediaFile.getAbsolutePath();
                                USB_OK = true;
                            }
                        }
                        // Log.v("tv", "path=" + path);

                        if (USB_OK) {
                            int PLAY_SOURCE_TYPE_LOCAL_FILE = 0;// LOCAL FILE
                            Intent itent = new Intent();
                            Bundle mData = new Bundle();
                            int currPlayPos = 0;
                            ArrayList<Map<String, Object>> videoPlayNodeList = new ArrayList<Map<String, Object>>();
                            HashMap<String, Object> movieNode = new HashMap<String, Object>();
                            movieNode.put("title", "VIDEO.MP4");
                            movieNode.put("cn", 1);
                            String[] str = new String[]{path};
                            movieNode.put("playUrls", str);
                            videoPlayNodeList.add(movieNode);
                            mData.putInt("playSourceType", PLAY_SOURCE_TYPE_LOCAL_FILE);
                            mData.putInt("curPos", currPlayPos);
                            itent.putExtra("movieNode", videoPlayNodeList);
                            itent.putExtras(mData);
                            itent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            ComponentName comp = new ComponentName(
                                    "com.homwee.mmp.fileexplorer",
                                    "com.changhong.mmp.videoplayer.ChangHongVideoPlayerActivity");
                            itent.setComponent(comp);
                            try {
                                context.startActivity(itent);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                            }

                        } else {
                            Intent it = new Intent();
                            Bundle bun = new Bundle();
                            bun.putInt("changhong.fileexplorer.media.type",
                                    FILE_EXPLORER_TYPE_ALL);
                            it.putExtras(bun);
                            ComponentName compall = new ComponentName(
                                    "com.homwee.mmp.fileexplorer",
                                    "com.changhong.mmp.fileexplorer.ChangHongFileExplorerActivity");
                            it.setComponent(compall);
                            it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            try{
                                context.startActivity(it);
                            }
                            catch(ActivityNotFoundException e){
                                Toast.makeText(mContext, "Please install media", Toast.LENGTH_LONG).show();
                            }
                        }
                        showToast("USB");
                    }
                }
                break;
                // F7 CI INFO
                // case KeyEvent.KEYCODE_BUTTON_16: {
				case KeyEvent.KEYCODE_CUT:{
                    if (MtkTvCI.getInstance(0).getSlotActive()) {
                        updateStateService(mContext, 1, "CI OK", COLOR_GREEN);
                        showToast("CI OK");
                    } else {
                        updateStateService(mContext, 1, "CI ERROR", COLOR_RED);
                        showToast("CI ERROR");
                    }
                }
                break;
                // F13 CEC
                case KeyEvent.KEYCODE_MANNER_MODE: {
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_control_enabled", 1);
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_arc_control_enabled", 1);
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_control_auto_device_off_enabled", 1);
                    Settings.Global.putInt(context.getContentResolver(),
                            "hdmi_control_auto_wakeup_enabled", 1);
                    
                    updateStateService(mContext, 1, "CEC ON", COLOR_GREEN);
                    showToast("ARC/CEC ON");
                }

                break;
                // Factory HDMI
                case KeyEvent.KEYCODE_BOOKMARK: {
                    Log.d("zcj","getCurSource return :"+getCurSource()+"isHDMIEnableByIndex return :"+isHDMIEnableByIndex(context,2));
                    if (getCurSource().equals("HDMI 1")&&isHDMIEnableByIndex(context,2)) {
                        changeSourceByBroadcast(context, "HDMI 2",-1);
                    } else if (getCurSource().equals("HDMI 2")&&isHDMIEnableByIndex(context,3)) {
                        changeSourceByBroadcast(context, "HDMI 3",-1);
                    } else if (getCurSource().equals("HDMI 3")) {
                        if (isHDMIEnableByIndex(context,4)&&sourceMap.containsKey("HDMI 4")) {
                            changeSourceByBroadcast(context, "HDMI 4",-1);
                        } else {
                            changeSourceByBroadcast(context, "HDMI 1",-1);
                        }
                    } else if (getCurSource().equals("HDMI 4")) {
                        changeSourceByBroadcast(context, "HDMI 1",-1);
                    } else {
                        changeSourceByBroadcast(context, "HDMI 1",-1);
                    }

                }
                break;
                // WIFI
                case KeyEvent.KEYCODE_STB_POWER: {
                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        if ("com.android.tv.settings.connectivity.NetworkActivity"
                                .equals(running.baseActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }
                    if (!factoryActive) {
                        Intent netIntent = new Intent(
                                "android.settings.WIFI_SETTINGS");
                        netIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        try {
                            mContext.startActivity(netIntent);
                            boolean wifiEnable = isWifiEnable(mContext);
                            updateStateService(mContext, 1, wifiEnable?"WIFI OK":"WIFI ERROR", wifiEnable?COLOR_GREEN:COLOR_RED);
                            if(wifiEnable == false){
		            WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                            wifiManager.startScan();
                        new Thread() {
                            public void run() {
                                try {
                                     Thread.sleep(3000);
				     boolean wifiEnable = isWifiEnable(mContext);
				     updateStateService(mContext, 1, wifiEnable?"WIFI OK":"WIFI ERROR", wifiEnable?COLOR_GREEN:COLOR_RED);
                                     
                                } catch (Exception e) {
                                }
                            }
                        }.start();
                        
                            }
                            
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new Thread() {
                            public void run() {
                                try {
                                    Instrumentation inst = new Instrumentation();
                                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                                } catch (Exception e) {
                                }
                            }
                        }.start();
                    }

                }

                break;
                // LAN
                case KeyEvent.KEYCODE_STB_INPUT: {
                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        if ("com.homwee.factory.FactoryListInfoActivity"
                                .equals(running.baseActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }

                    if (!factoryActive) {
                        Log.v("zcj", "keycode=KEYCODE_CHMIR_WIRED");
                        Intent LANIntent = new Intent();
                        LANIntent.setComponent(new ComponentName(
                                "com.homwee.factory",
                                "com.homwee.factory.FactoryListInfoActivity"));
                        LANIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        LANIntent.putExtra("CheckItem", LAN_CHECK);
                        context.startActivity(LANIntent);
                        boolean lanStatus = factorySetting.isLanConnected();

                        updateStateService(mContext, 1, "LAN "+  (lanStatus?"OK":"FAIL"), lanStatus?COLOR_GREEN:COLOR_RED);
                    } else {
                        Log.v("tv", "s kill");
                        ((Activity) FactoryListInfoActivity.mContext).finish();
                    }
                }

                break;
                // Balance
                case KeyEvent.KEYCODE_AVR_POWER: {
                    //int balance = factorySetting.getBalance();
                    int balance = 0;
                    try{
                    balance = Settings.Global.getInt(context.getContentResolver(), "sound_balance");
                    if (balance != -50 && balance != 50 && balance != 0) {
                        balance = 0;
                    }

                    if (balance <= 0) {
                        balance += 50;
                    } else {
                        balance = -50;
                    }
                    //factorySetting.setBalance(balance);
		    Settings.Global.putInt(context.getContentResolver(), "sound_balance", balance);
                     } catch (Exception ex) {
                         ex.printStackTrace();
                     }
                    if (balance == -50) {
                        showToast("L");
                        updateStateService(mContext,1,"L",COLOR_WHITE);
                    } else if (balance == 50) {
                        showToast("R");
                        updateStateService(mContext,1,"R",COLOR_WHITE);
                    } else {
                        showToast("0");
                        updateStateService(mContext,1,"0",COLOR_WHITE);
                    }

                    Log.v("tv", "setSoundBalance " + balance);
                }

                break;
                // Customer Channel Preset
                case KeyEvent.KEYCODE_AVR_INPUT:
                    if(mBrand.equals("Philco") && mProduct.contains("ISDB")){
                        boolean factoryActive = false;
                        ActivityManager mActivityManager = (ActivityManager) context
                                .getSystemService(Context.ACTIVITY_SERVICE);
                        List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                                .getRunningTasks(100);
                        for (ActivityManager.RunningTaskInfo running : appList) {
                            Log.v("tv",
                                    "factory1 =" + running.baseActivity.getClassName());
                            if ("com.homwee.factory.FactoryActivity"
                                    .equals(running.baseActivity.getClassName())) {
                                factoryActive = true;
                                break;
                            }

                        }

                        if (!factoryActive) {
                            Log.v("tv", "ss");
                            Intent myIntent = new Intent();
                            myIntent.setComponent(new ComponentName(
                                    "com.homwee.factory",
                                    "com.homwee.factory.FactoryActivity"));
                            myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            myIntent.putExtra("PageIndex", 1);
                            context.startActivity(myIntent);
                        } else {
                            Log.v("tv", "s kill");
                            ((Activity) FactoryActivity.mContext).finish();
                        }

                        FactoryModeMenu.refresh(context);
                    }else {
                        if (isChannelDirExists(factorySetting)) {
                            boolean loadret = loadChannelList(context, factorySetting);
                            if (loadret == true) {
                                FactoryModeMenu.refresh(mContext);
                                Intent TVtoolServiceIntent = new Intent(mContext,
                                        ShowFactoryTipsService.class);
                                TVtoolServiceIntent
                                        .setAction("ShowFactoryTipsService");
                                TVtoolServiceIntent.putExtra("Tips", "SKD Reset OK");
                                mContext.startService(TVtoolServiceIntent);
                                updateStateService(mContext, 1, "SKD Reset OK", COLOR_GREEN);
                            } else {
                                Toast.makeText(context, "load chanellist failed", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(context, context.getString(R.string.factory_pagethree_channellist_folder_no_exits), Toast.LENGTH_LONG).show();
                        }
                    }

                    break;

                // F12 USB Upgrade
                case KeyEvent.KEYCODE_TV_SATELLITE_SERVICE: {
			/*
				 if (factorySetting.findUsbDir()) {
			   PowerManager mPowerManager = (PowerManager) mContext
				   .getSystemService(Context.POWER_SERVICE);
			   mPowerManager.shutdown(false, "shutdown", false); 
                   } else {
                           
                           Toast.makeText(context,context.getString(R.string.factory_reciver_no_usb), Toast.LENGTH_LONG).show();
                   }
			*/
                    if (mProduct.contains("ISDB") && mBrand.equals("Philco")) {
                        Intent intentSearch = new Intent();
                        intentSearch
                                .setClassName("com.mediatek.wwtv.tvcenter",
                                        "com.mediatek.wwtv.setting.base.scan.ui.ScanViewActivity");
                        intentSearch.putExtra("ActionID", "tv_dvbt_single_rf_scan");
                        intentSearch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intentSearch);
                    } else {
                        boolean factoryActive = false;
                        ActivityManager mActivityManager = (ActivityManager) context
                                .getSystemService(Context.ACTIVITY_SERVICE);
                        List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                                .getRunningTasks(100);
                        for (ActivityManager.RunningTaskInfo running : appList) {
                            Log.v("tv",
                                    "factory1 =" + running.baseActivity.getClassName());
                            if ("com.homwee.factory.FactoryListInfoActivity"
                                    .equals(running.baseActivity.getClassName())) {
                                factoryActive = true;
                                break;
                            }

                        }

                        if (!factoryActive) {
                            Log.v("wql", "keycode=KEYCODE_CHMIR_F12");
                            Intent KsyStatusIntent = new Intent();
                            KsyStatusIntent.setComponent(new ComponentName(
                                    "com.homwee.factory",
                                    "com.homwee.factory.FactoryListInfoActivity"));
                            KsyStatusIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            KsyStatusIntent.putExtra("CheckItem", KEY_STATUS_CHECK);
                            context.startActivity(KsyStatusIntent);
                        } else {
                            Log.v("tv", "s kill");
                            ((Activity) FactoryListInfoActivity.mContext).finish();
                        }
                    }
                }

                break;
                // F15 White Balance
                case KeyEvent.KEYCODE_NAVIGATE_NEXT: {

                    PackageInfo packageInfo = null;
                    try {
                        packageInfo = context.getPackageManager().getPackageInfo(
                                "com.homwee.overseaswbadjust", 0);
                    } catch (NameNotFoundException e1) {
                        // TODO Auto-generated catch block
                        packageInfo = null;
                        e1.printStackTrace();
                    }
                    if (packageInfo != null) {
                        try {
                            Intent intentServer = new Intent();
                            intentServer
                                    .setClassName("com.homwee.overseaswbadjust",
                                            "com.homwee.overseaswbadjust.WBAdjustService");
                            mContext.startService(intentServer);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
					updateStateService(mContext, 1, "W/B", COLOR_GREEN);
                }
                break;
                // DVBC/DVBT/DVBS
                case KeyEvent.KEYCODE_MEDIA_CLOSE: {
                    if (mProduct.contains("DVB")) {
                        if (!isLiveTVRunning(mContext)) {
                            MtkTvMultiView.getInstance().setChgSource(true);
                            changeSourceByBroadcast(context, "DTV",-1);
                        }else if(factorySetting.isColRegion() && getCurrentAnt().equals("AIR")){
                            MtkTvMultiView.getInstance().setChgSource(true);
                            Log.d(TAG,"need set ChgSource to 1 .");
                            changeSourceByBroadcast(context, "ATV",-1);
                        }
                    }else{
                        //if (!isCurSourceIsTv()) {
                            changeSourceByBroadcast(context, "TV",-1);
                        //}
                    }
                    if(!isInStartPage(context)) {
                        mHandler.removeCallbacks(mRunForSetAntenna);
                        mHandler.postDelayed(mRunForSetAntenna, 260);
                    }

                        //send msg
                        mHandler.removeMessages(MESSAGE_UPDATE_KEY);
                        Message message = mHandler.obtainMessage();
                        message.what = MESSAGE_UPDATE_KEY;
                        message.obj = mContext;
                        Bundle bundle = new Bundle();    
                        bundle.putString("keyret","ANT");
                        bundle.putInt("color",COLOR_GREEN); 
                        message.setData(bundle);
                        mHandler.sendMessageDelayed(message, 2000);

//                        updateStateService(mContext, 1, getCurrentAnt(), COLOR_WHITE);
                    /*
                     * int curAntMode = MtkTvConfig.getInstance().getConfigValue(
                     * MtkTvConfigType.CFG_BS_BS_SRC); Log.d(TAG,
                     * "curAntMode:"+curAntMode);
                     *
                     * switch ((curAntMode + 1) % 3) { case 0: showToast(context
                     * .getString(R.string.factory_reciver_source_tv_air)); break;
                     * case 1: showToast(context
                     * .getString(R.string.factory_reciver_source_tv_cable)); break;
                     * case 2: showToast(context
                     * .getString(R.string.factory_reciver_source_tv_satallite));
                     * break;
                     *
                     * default: break; } MtkTvConfig.getInstance().setConfigValue(
                     * MtkTvConfigType.CFG_BS_BS_SRC, (curAntMode + 1) % 3);
                     */

                    // showToast(context,"");
                }
                break;

                // F4 SCART
                case KeyEvent.KEYCODE_FORWARD: {
                    //changeSourceByBroadcast(context, "SCART");
                    boolean barcodeActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        Log.v("tv",
                                "factory2 =" + running.topActivity.getClassName());
                        if ("com.homwee.factory.BarCodeShowActivity"
                                .equals(running.topActivity.getClassName())) {
                            barcodeActive = true;
                            break;
                        }

                    }
                    if (!barcodeActive) {
                        Log.v("tv", "barcode start");
                    Intent barcodeIntent = new Intent();
                    barcodeIntent.setComponent(new ComponentName(
                                "com.homwee.factory",
                                "com.homwee.factory.BarCodeShowActivity"));
                    barcodeIntent.addFlags(barcodeIntent.FLAG_ACTIVITY_NEW_TASK);
		    context.startActivity(barcodeIntent);
                    } else {
                        Log.v("tv", "barcode kill");
                        Intent intentstopBarCode = new Intent();
                        intentstopBarCode
                                .setAction("com.homwee.action.STOP_BARCODE_SCAN");
                        context.sendBroadcast(intentstopBarCode);
                    }
                }
                break;
                // F10 Data Show
                case KeyEvent.KEYCODE_REFRESH: {
                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        if ("com.homwee.factory.FactoryActivity"
                                .equals(running.baseActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }

                    if (!factoryActive) {
                        Log.v("tv", "keycode=F10");
                        Intent myIntent = new Intent();
                        myIntent.setComponent(new ComponentName(
                                "com.homwee.factory",
                                "com.homwee.factory.FactoryActivity"));
                        myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        //myIntent.putExtra("CheckItem",KEY_STATUS_CHECK);
                        context.startActivity(myIntent);
                    } else {
                        Log.v("tv", "s kill");
                        ((Activity) FactoryActivity.mContext).finish();
                    }

                    FactoryModeMenu.refresh(context);
                    boolean keyCheck = isAllKeyExist(factorySetting);
                    updateStateService(mContext, 1, keyCheck?"KEY OK":"KEY FAIL", keyCheck?COLOR_GREEN:COLOR_RED);
                }
                break;

                // PC/VGA
//                case KeyEvent.KEYCODE_BUTTON_11: {
//                    changeSourceByBroadcast(context, "VGA");
//                    showToast(context
//                            .getString(R.string.factory_reciver_source_vga));
//                }
//                break;

                // F6 BLUETOOTH
                case KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN: {
                    boolean isBTEnable = isBTEnable(context);
                    updateStateService(context, 1, isBTEnable?"BT OK":"BT FAIL", isBTEnable?COLOR_GREEN:COLOR_RED);
                    Intent myIntent = new Intent();
                    myIntent.setComponent(new ComponentName(
                            "com.android.tv.settings",
                            "com.android.tv.settings.accessories.AddAccessoryActivity"));
                    myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(myIntent);
                }

                break;

                // BAR_CODE
                case KeyEvent.KEYCODE_PLUS:{
				boolean factoryActive = false;
				ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
				List<ActivityManager.RunningTaskInfo> appList = mActivityManager.getRunningTasks(100);
				for (ActivityManager.RunningTaskInfo running : appList) {
					Log.v("tv", "factory1 =" + running.baseActivity.getClassName());
					Log.v("tv", "factory2 =" + running.topActivity.getClassName());
					if ("com.homwee.factory.FactoryExtraInfoActivity".equals(running.topActivity.getClassName())) {
						factoryActive = true;
						break;
					}

				}

				if (isFactoryMMode(context) && !factoryActive) {
					Intent intentForFactoryExtra = new Intent();
					intentForFactoryExtra.setClass(context, FactoryExtraInfoActivity.class);
					intentForFactoryExtra.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intentForFactoryExtra);
				} else {
					FactoryExtraInfoActivity.instance.finish();
				}

				FactoryModeMenu.refresh(mContext);
			}
                    break;
                // F11
                case KeyEvent.KEYCODE_TV_AUDIO_DESCRIPTION: {
                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        if ("com.homwee.factory.FactoryListInfoActivity"
                                .equals(running.baseActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }
                    new Thread((new Runnable() {
                        @Override
                        public void run() {
                            if (!isAllKeyExist(factorySetting)) {
                                if (isFirstUpdateKey(factorySetting)) {
                                    updateAllKeys(context, factorySetting, mContext, true);
                                }
                            }
                        }
                    })).start();


                    if (!factoryActive) {
                        Log.v("wql", "keycode=KEYCODE_CHMIR_F11");
                        Intent USBIntent = new Intent();
                        USBIntent.setComponent(new ComponentName(
                                "com.homwee.factory",
                                "com.homwee.factory.FactoryListInfoActivity"));
                        USBIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        USBIntent.putExtra("CheckItem", USB_CHECK);
                        context.startActivity(USBIntent);
                    } else {
                        Log.v("tv", "s kill");
                        ((Activity) FactoryListInfoActivity.mContext).finish();
                    }

                }

                break;
                // F18 backup key F1
                case KeyEvent.KEYCODE_BUTTON_14: {
                        Log.v("lhtest", "keycode=KEYCODE_TV_INPUT_COMPONENT_1");

                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        if ("com.homwee.factory.FactoryListInfoActivity"
                                .equals(running.baseActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }
                    new Thread((new Runnable() {
                        @Override
                        public void run() {
                            if (!isAllKeyExist(factorySetting)) {
                                if (isFirstUpdateKey(factorySetting)) {
                                    updateAllKeys(context, factorySetting, mContext, true);
                                }
                            }
                        }
                    })).start();


                    if (!factoryActive) {
                        Log.v("wql", "keycode=KEYCODE_CHMIR_F11");
                        Intent USBIntent = new Intent();
                        USBIntent.setComponent(new ComponentName(
                                "com.homwee.factory",
                                "com.homwee.factory.FactoryListInfoActivity"));
                        USBIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        USBIntent.putExtra("CheckItem", EEPROM_STATUS_SHOW);
                        context.startActivity(USBIntent);
                    } else {
                        Log.v("tv", "s kill");
                        ((Activity) FactoryListInfoActivity.mContext).finish();
                    }


                }
                    break;

                // Screen Test backup key F2
                case KeyEvent.KEYCODE_NAVIGATE_PREVIOUS: {
                    //set backlight & dreamTime
                    int backlightInt=1;
                    int dreamTimeInt=1;
                    int twoHourInt=7200000;
                    try{
                        backlightInt = Settings.Global.getInt(context.getContentResolver(), "picture_backlight");
                        dreamTimeInt=Settings.System.getInt(context.getContentResolver(), SCREEN_OFF_TIMEOUT);
                    }catch (Settings.SettingNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(backlightInt!=100||dreamTimeInt!=twoHourInt){
                        Settings.Global.putInt(context.getContentResolver(), "picture_backlight", 100);
                        Settings.System.putInt(context.getContentResolver(), SCREEN_OFF_TIMEOUT, twoHourInt);
                    }
                }
				break;

                // MAC backup key F3
                case KeyEvent.KEYCODE_BUTTON_15: {
                    if (!getMacBarShow(context)) {
                        Log.d(TAG, "cyf test F4 start show");
                        setMacBarShow(context, 1);
                        Intent intentForBarServer = new Intent(
                                "com.homwee.macbarcode.BarCodeService");
                        intentForBarServer.setPackage("com.homwee.factory");
                        mContext.startService(intentForBarServer);
                    } else {
                        Log.d(TAG, "cyf test F4 stop show");
                        setMacBarShow(context, 0);
                        Intent intentForBarCode = new Intent();
                        intentForBarCode
                                .setAction("com.homwee.macbarcode.stopservice");
                        mContext.sendBroadcast(intentForBarCode);
                    }
                    /*remove extraInfo
                    boolean factoryActive = false;
                    ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                            .getRunningTasks(100);
                    for (ActivityManager.RunningTaskInfo running : appList) {
                        Log.v("tv",
                                "factory1 =" + running.baseActivity.getClassName());
                        Log.v("tv",
                                "factory2 =" + running.topActivity.getClassName());
                        if ("com.homwee.factory.FactoryExtraInfoActivity"
                                .equals(running.topActivity.getClassName())) {
                            factoryActive = true;
                            break;
                        }

                    }
                    
                    if(isFactoryMMode(context)&&!factoryActive){
                    	Intent intentForFactoryExtra=new Intent();
                    	intentForFactoryExtra.setClass(context,FactoryExtraInfoActivity.class);
                    	context.startActivity(intentForFactoryExtra);
                    }
                    else {
                    	FactoryExtraInfoActivity.instance.finish();
                    }
                    
                    FactoryModeMenu.refresh(mContext);
					*/
                }

                break;
                // PC XIANGWEI backup key F4
                case KeyEvent.KEYCODE_BUTTON_4:

                    break;
                // FCT Aging ON
                case KeyEvent.KEYCODE_NAVIGATE_IN: {
                    factorySetting.setAgingModel(1);
                }
                break;
                // FCT Aging OFF
                case KeyEvent.KEYCODE_NAVIGATE_OUT: {
                    factorySetting.setAgingModel(0);
                }
                break;
                // FCT HDMI1
                case KeyEvent.KEYCODE_TV_INPUT_HDMI_1: {
                    changeSourceByBroadcast(context, "HDMI 1",-1);
                }
                break;
                // FCT HDMI2
                case KeyEvent.KEYCODE_TV_INPUT_HDMI_2: {
                    changeSourceByBroadcast(context, "HDMI 2",-1);
                }
                break;
                // FCT HDMI3
                case KeyEvent.KEYCODE_TV_INPUT_HDMI_3: {
                    changeSourceByBroadcast(context, "HDMI 3",-1);
                }
                break;
                // FCT HDMI4
                case KeyEvent.KEYCODE_TV_INPUT_HDMI_4: {
                    changeSourceByBroadcast(context, "HDMI 4",-1);
                }
                break;
                // FCT KEY Upgrade
                case KeyEvent.KEYCODE_CALL: {
                    updateStateService(mContext, 1, "Key Write", COLOR_WHITE);
                    updateAllKeys(context, factorySetting, mContext, false);
                    if(isAllKeyExist(factorySetting)){
                        updateStateService(mContext, 1, "Key Write", COLOR_GREEN);
                    }else {
                        updateStateService(mContext,1,"Key Write",COLOR_RED);
                    }
                    if (isPanelDirExists(factorySetting)) {
                        updatePanelOnBoot(context, factorySetting);
                    }
                }

                break;
                // FCT ANT AIR
                case KeyEvent.KEYCODE_ENDCALL: {
                    if(mProduct.contains("DVB")) {
                        //if (!isCurSourceIsDtv()) {
                            MtkTvMultiView.getInstance().setChgSource(true);
                            Log.d(TAG, "need set ChgSource to 1 .");
                            changeSourceByBroadcast(context, "DTV",0);
                        //}
                    }else{
                        //if (!isCurSourceIsTv()) {
                            changeSourceByBroadcast(context, "TV",-1);
                        //}
                    }

                    if(!isInStartPage(context)){
                        MtkTvConfig.getInstance().setConfigValue(
                                MtkTvConfigType.CFG_BS_BS_SRC,
                                MtkTvConfigTypeBase.ACFG_BS_SRC_AIR);
                        MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff,0);
                        channelInfo.setChannelId(0xffffffff);
                        MtkTvBroadcast.getInstance().channelSelect(channelInfo,false);
                        showToast(context
                                .getString(R.string.factory_reciver_source_tv_air));
                        updateStateService(mContext, 1, context.getString(R.string.factory_reciver_source_tv_air), COLOR_WHITE);

                    }

                }
                break;
                // FCT ANT CABLE
                case KeyEvent.KEYCODE_TV_ANTENNA_CABLE: {
                    if(mProduct.contains("DVB")){
                        if (!factorySetting.isColRegion()) {
                            MtkTvMultiView.getInstance().setChgSource(true);
                            Log.d(TAG, "need set ChgSource to 1 .");
                            changeSourceByBroadcast(context, "DTV",1);
                        }else{
							//is ColRegion
                            MtkTvMultiView.getInstance().setChgSource(true);
                            Log.d(TAG, "need set ChgSource to 1 .");
                            changeSourceByBroadcast(context, "ATV",-1);
                        }
                    }else{
                        //if(!isCurSourceIsTv()){
                            changeSourceByBroadcast(context, "TV",-1);
                        //}
                    }
                    if(!isInStartPage(context)) {
                        MtkTvConfig.getInstance().setConfigValue(
                                MtkTvConfigType.CFG_BS_BS_SRC,
                                MtkTvConfigTypeBase.ACFG_BS_SRC_CABLE);
                        MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff,0);
                        channelInfo.setChannelId(0xffffffff);
                        MtkTvBroadcast.getInstance().channelSelect(channelInfo,false);
                        showToast(context
                                .getString(R.string.factory_reciver_source_tv_cable));
                        updateStateService(mContext, 1, context.getString(R.string.factory_reciver_source_tv_cable), COLOR_WHITE);
                    }
                }
                break;
                // FCT ANT SATELLITE
                case KeyEvent.KEYCODE_TV_SATELLITE: {
                    //if (!isCurSourceIsDtv()) {
                        MtkTvMultiView.getInstance().setChgSource(true);
                        Log.d(TAG, "need set ChgSource to 1 .");
                        changeSourceByBroadcast(context, "DTV",2);
                    //}
                    if (!isInStartPage(context)) {

                        MtkTvConfig.getInstance().setConfigValue(
                                MtkTvConfigType.CFG_BS_BS_SRC, 3);//MtkTvConfigTypeBase.ACFG_BS_SRC_SAT); //3 is set to general SAT
                        MtkTvChannelInfoBase channelInfo = new MtkTvChannelInfoBase(0xffff, 0);
                        channelInfo.setChannelId(0xffffffff);
                        MtkTvBroadcast.getInstance().channelSelect(channelInfo, false);

                        showToast(context
                                .getString(R.string.factory_reciver_source_tv_satallite));
                        updateStateService(mContext, 1, context.getString(R.string.factory_reciver_source_tv_satallite), COLOR_WHITE);
                    }
                }
                break;

                default:
                    Log.d(TAG, "default:" + mKeyCode);
                    break;
            }

            FactoryModeMenu.refresh(context);

            Log.v("tv", "FactoryKeyReciver keyCode =" + mKeyCode);
        }

    }

    private boolean loadChannelList(Context context,
                                 final FactorySetting factorySetting) {
        if (factorySetting.findUsbDir()) {
            if (factorySetting.getFile(Contants.PATH_CHANNEL).exists()) {
//                broadcastIntentOut(context,
//                        "mtk.intent.event.preset.channel.start");
//                factorySetting.loadChannelList(1);
//                broadcastIntentOut(context,
//                        "mtk.intent.event.preset.channel.end");
//                showToast(context
//                       .getString(R.string.factory_pagethree_channellist_load_success));
//                factorySetting.selectfirstChannel();
                context.sendBroadcast(new Intent(
                        "mtk.intent.event.preset.channel.start"));
                factorySetting.loadChannelList(1);
                context.sendBroadcast(new Intent(
                        "mtk.intent.event.preset.channel.end"));
                showToast(context
                        .getString(R.string.factory_pagethree_channellist_load_success));
                factorySetting.selectfirstChannel();
                return true;
            } else {
                showToast(context
                        .getString(R.string.factory_pagethree_channellist_folder_no_exits));
                return false;
            }

        } else {
            showToast(context.getString(R.string.factory_reciver_no_usb));
                return false;
        }
    }

    private void updatePanelOnBoot(final Context context,
                                   final FactorySetting factorySetting) {
        if (factorySetting.findUsbDir()) {
            final String mFileName = Contants.FACTORY_PAGE2_PANEL_UPDATE_PATH;
            final File pannelUpdateFile = factorySetting.getFile(mFileName);
            if (pannelUpdateFile.exists()) {

                final File[] panel_files = pannelUpdateFile.listFiles();
                if (panel_files.length == 0) {
                    // showToast("Can't find any file in panel directory");
                    return;
                } else {
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            File file = panel_files[0];
                            factorySetting.copyFile(file.getAbsolutePath(),
                                    Contants.FACTORY_PAGE2_PANEL_PATH + "/"
                                            + file.getName());
                            factorySetting.setPanelName(file.getName().replace(
                                    ".ini", ""));
                            MtkTvFApiSystem.getInstance().setEmmcEnvVar(
                                    "db_table", "0");
                            showToast("update panel ok");
                        }
                    }, 100);
                }
            } else {
                // showToast("Can't find panel directory!");
                return;
            }
            /*
             * PowerManager pManager = (PowerManager) mContext
             * .getSystemService(mContext.POWER_SERVICE); pManager.reboot("");
             * showToast("reboot......");
             */

        } else {
            // showToast("Please insert USB,Can't find USB!");
        }
    }

    private int updateAllKeys(Context context,
                               final FactorySetting factorySetting, final Context mContext,
                               boolean isBootUpdate) {
        if (factorySetting.findUsbDir()) {

            // String mShow = "Result:\n";
            for (int id = 0; id < Contants.mKeyPathStrings.length; id++) {
                mKeyDirs[id] = factorySetting
                        .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR + "/"
                                + Contants.mKeyPathStrings[id]);
            }
            for (int index = 0; index < mKeyDirs.length; index++) {
                if (mKeyDirs[index].exists()) {
                    mKeyDirExistsBooleans[index] = true;
                    mKeyFileUpdatesBooleans[index]=false;
                    // get the first key
                    if (mKeyDirs[index].listFiles().length > 0) {
                        mKeyFileExistsBooleans[index] = true;
                        File updatefile = mKeyDirs[index].listFiles()[0];
                        switch (index) {
                            case Contants.KEY_TAG_CIPLUS: {
                                if (factorySetting.isDTVCIPlusKeyExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setCIPlusKey(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;
                            /*case Contants.KEY_TAG_DEVICEID: {
                                if (factorySetting.isDeviceIdExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setDeviceIDByPath(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;*/
                            case Contants.KEY_TAG_NETFLIX: {
                                if (factorySetting.isNETFLIXKeyExist()
                                        && factorySetting
                                        .getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setNetflixKey(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;

                            case Contants.KEY_TAG_HDCP: {
                                if (factorySetting.isHDCPKey2XExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setHdcpKey2x(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;
                            case Contants.KEY_TAG_HDCP14: {
                                if (factorySetting.isHDCPKey1XExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setHdcpKey1x(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;
                            case Contants.KEY_TAG_KEYMASTER: {
                                if (factorySetting.isKeyMasterExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setKeyMaster(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;
                            case Contants.KEY_TAG_WIDEVINE: {
                                if (factorySetting.isWidevineKeyExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setWidevineKey(updatefile
                                                    .getAbsolutePath())&&
                                            factorySetting.setDeviceID(updatefile.getName().substring(0, updatefile.getName().indexOf(".")));

                                }
                            }
                            break;

                            case Contants.KEY_TAG_MAC: {
                                if (factorySetting.isMacExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setMACAddr(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;
                            case Contants.KEY_TAG_PLAYREADY: {
                                if (factorySetting.isPlayReadyKeyExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    boolean ret1 = false, ret2 = false;
                                    for (int i = 0; i < mKeyDirs[index].listFiles().length; i++) {
                                        File file = mKeyDirs[index].listFiles()[i];
                                        if (file.getAbsolutePath().contains(
                                                Contants.KEY_STRING_PLAYREADY_1)) {
                                            ret1 = factorySetting
                                                    .setPlayReadyKey_1(file
                                                            .getAbsolutePath());
                                        } else if (file.getAbsolutePath().contains(
                                                Contants.KEY_STRING_PLAYREADY_2)) {
                                            ret2 = factorySetting
                                                    .setPlayReadyKey_2(file
                                                            .getAbsolutePath());
                                        } else {

                                        }
                                        Log.d("zcj", file.getAbsolutePath());
                                    }

                                    mKeyFileUpdatesBooleans[index] = ret1 && ret2 && factorySetting.setPlayReadyKeyToIni("OK");
                                }
                            }
                            break;
							/*
                            case Contants.KEY_TAG_PLAYREADY25: {
                                if (factorySetting.isPlayReadyKey25Exist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    boolean ret1 = false, ret2 = false;
                                    for (int i = 0; i < mKeyDirs[index].listFiles().length; i++) {
                                        File file = mKeyDirs[index].listFiles()[i];
                                        if (file.getAbsolutePath().contains(
                                                Contants.KEY_STRING_PLAYREADY25_1)) {
                                            ret1 = factorySetting
                                                    .setPlayReadyKey25_1(file
                                                            .getAbsolutePath());
                                        } else if (file.getAbsolutePath().contains(
                                                Contants.KEY_STRING_PLAYREADY25_2)) {
                                            ret2 = factorySetting
                                                    .setPlayReadyKey25_2(file
                                                            .getAbsolutePath());
                                        } else {

                                        }
                                        Log.d("zcj", file.getAbsolutePath());
                                    }

                                    mKeyFileUpdatesBooleans[index] = ret1 && ret2 && factorySetting.setPlayReadyKey25ToIni("OK");
                                }
                            }
                            break;
							*/
                            case Contants.KEY_TAG_WEBPLATFORM_CA: {
                                if (factorySetting.isCLIENTCAKeyExist()
                                        && factorySetting
                                        .getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    String caKeyPath=updatefile.getParentFile().getAbsolutePath();
                                    Log.d("CHFactoryTEST",caKeyPath);
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setCLIENTCAKey(caKeyPath);
                                }
                            }
                            break;
                            case Contants.KEY_TAG_PROJECT: {
                                if (factorySetting.isProjectIdExist()
                                        && factorySetting.getKeyUpgradeForce() == 0) {
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                } else {
                                    mKeyFileTvExistBooleans[index] = false;
                                    mKeyFileUpdatesBooleans[index] = factorySetting
                                            .setProjectId(updatefile
                                                    .getAbsolutePath());
                                }
                            }
                            break;
                            case Contants.KEY_TAG_HASHKEY:{
                                if(!factorySetting.isHashKeyExist()
                                        || factorySetting.getHashKeyUpgradeForce()==0){
									String path=updatefile.getAbsolutePath().substring(0,updatefile.getAbsolutePath().lastIndexOf("/")+1);
                                    mKeyFileTvExistBooleans[index] = false;
									mKeyFileUpdatesBooleans[index]=factorySetting.setHashKey(path);
                                }else{
                                    mKeyFileTvExistBooleans[index] = true;
                                    mKeyFileUpdatesBooleans[index] = false;
                                }
                            }
                            break;

                        }

                        if (mKeyFileUpdatesBooleans[index]) {
                            if (index == Contants.KEY_TAG_PROJECT
                                    || index == Contants.KEY_TAG_PLAYREADY
                                    || index == Contants.KEY_TAG_WEBPLATFORM_CA) {
                                Log.d("zcj", "hash key playready");
                            }
                            else if(index == Contants.KEY_TAG_NETFLIX){
                            	//delete is move to set Function
                            	/*
                                boolean isdelete = factorySetting
                                        .deleteDirByPath(updatefile
                                                .getAbsolutePath());
                                                */
                            }
                            else {
                            	//delete is move to set Function
                            	/*
                                boolean isdelete = factorySetting
                                        .deleteFileByPath(updatefile
                                                .getAbsolutePath());
                                Log.d("zcj", updatefile.getAbsolutePath()
                                        + " isdelete="
                                        + (isdelete ? "true" : "false"));
                                        */
                            }
                        }
                    } else {
                        mKeyFileExistsBooleans[index] = false;
                        mKeyFileUpdatesBooleans[index] = false;
                        mKeyFileTvExistBooleans[index] = false;
                    }
                } else {
                    mKeyFileExistsBooleans[index] = false;
                    mKeyDirExistsBooleans[index] = false;
                    mKeyFileUpdatesBooleans[index] = false;
                    mKeyFileTvExistBooleans[index] = false;
                }
            }

            mKeyFileExistsBooleans[Contants.KEY_TAG_DEVICEID]=mKeyFileExistsBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
            mKeyDirExistsBooleans[Contants.KEY_TAG_DEVICEID]=mKeyDirExistsBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
            mKeyFileUpdatesBooleans[Contants.KEY_TAG_DEVICEID]=mKeyFileUpdatesBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
            mKeyFileTvExistBooleans[Contants.KEY_TAG_DEVICEID]=mKeyFileTvExistBooleans[Contants.KEY_TAG_WIDEVINE];//device result widevine key
           // copySpecialKeyFile(factorySetting);
            if(!isBootUpdate) {

//                mFactoryKeyResultDialog = FactoryKeyResultDialog.getInstance(
//                        mContext, mKeyDirExistsBooleans, mKeyFileExistsBooleans,
//                        mKeyFileUpdatesBooleans, mKeyFileTvExistBooleans);
                mFactoryKeyResultDialog = new FactoryKeyResultDialog(
                        mContext, mKeyDirExistsBooleans,
                        mKeyFileExistsBooleans, mKeyFileUpdatesBooleans,
                        mKeyFileTvExistBooleans);

                mFactoryKeyResultDialog.getWindow().setType(
                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                mFactoryKeyResultDialog.show();
            }else{
                showToast("Boot on Burn Key Success");
            }
            return 0;
        } else {
            if (!isBootUpdate) {
                showToast(context.getString(R.string.factory_reciver_no_usb));
                return -1;
            }else{
                Log.d(TAG,"bootUpdateKey fail:USB not find!!!!");
                return -2;
            }
        }
    }

    /* add zeng */
    private boolean IsInspectionDebugOn() {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(
                    "com.changhong.overseasInspection.InspectionService") == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /* add zcj */
    private void init(Context context , FactorySetting factorySetting) {

        TvInputManager tvInputManager = (TvInputManager) context
                .getSystemService(Context.TV_INPUT_SERVICE);
        List<TvInputInfo> list = tvInputManager.getTvInputList();
        for (TvInputInfo info : list) {
            mUiSourceListInputName.add("content://android.media.tv/passthrough/" + info.getId().replace("/", "%2F"));
            Log.i(TAG, "id:" + "content://android.media.tv/passthrough/" + info.getId().replace("/", "%2F"));
        }

        if (mToast != null) {
            mToast.cancel();
            mToast = Toast.makeText(context, "start", Toast.LENGTH_SHORT);
        } else {
            mToast = Toast.makeText(context, "start", Toast.LENGTH_SHORT);
        }
        TextView tv = (TextView) mToast.getView().findViewById(
                com.android.internal.R.id.message);
        tv.setTextSize(30);
        initSourceName(factorySetting);
    }

    byte GetHDCPKeyByteChecksum(byte[] key) // cHdcpBuffer 1024B
    {
        byte cTemp = 0, cRet = 0;
        int i;
        for (i = 0; i < (512 - 1); i++) {
            cTemp += key[i];
        }
        cRet = (byte) (0x00 - cTemp);
        return cRet;
    }

    byte GetMiracastHDCPKeyByteChecksum(byte[] key) // cHdcpBuffer 1024B
    {
        byte cTemp = 0, cRet = 0;
        int i;
        for (i = 0; i < (1280 - 1); i++) {
            cTemp += key[i];
        }
        cRet = (byte) (0x00 - cTemp);
        return cRet;
    }

    private void initSourceName(FactorySetting factorySetting) {

        int compositeNum = 0;
        int size = MtkTvInputSource.getInstance().getInputSourceTotalNumber();

        for (int i = 0; i < size; i++) {
            MtkTvInputSource.InputSourceRecord record = new MtkTvInputSource.InputSourceRecord();
            MtkTvInputSource.getInstance().getInputSourceRecbyidx(i, record);

            inputList.add(record);
            String sourceTypeName;
            sourceTypeName = record.getInputType().name();
            Log.d(TAG, sourceTypeName);

            if (TextUtils.isEmpty(sourceTypeName)) {
                continue;
            } else {

                if (sourceTypeName.equalsIgnoreCase("TV")) {
                    if(mProduct.contains("DVB")) {
                        mUiSourceList.add("ATV");
                        mUiSourceList.add("DTV");
                        sourceMap.put("ATV", Contants.ATVUri);
                        sourceMap.put("DTV", Contants.DTVUri);
                    }else{
						mUiSourceList.add("TV");
                        sourceMap.put("TV", Contants.DTVUri);
                    }


                } else if (sourceTypeName.equalsIgnoreCase("COMPOSITE")) {
                    compositeNum = record.getInternalIdx();
                    if (compositeNum > 0) {// modify string for idx=0
                        if (compositeNum == 1) {
                            mUiSourceList.set(mUiSourceList.size() - 1,
                                    "Composite " + compositeNum);
                        }
                        mUiSourceList.add("Composite " + (compositeNum + 1));
                    } else {
                        mUiSourceList.add("Composite");
                        sourceMap.put("Composite", Contants.CompositeUri);
                    }
                } else if (sourceTypeName.equalsIgnoreCase("COMPONENT")) {
                    mUiSourceList.add("Component");
                    sourceMap.put("Component", Contants.ComponentUri);
                } else if (sourceTypeName.equalsIgnoreCase("VGA")) {
                    mUiSourceList.add("VGA");
                    sourceMap.put("VGA", Contants.VgaUri);
                } else if (sourceTypeName.equalsIgnoreCase("HDMI")) {
                    // if ((record.getInternalIdx() + 1) ==
                    // mTvInputSource.getMhlPortNum()) {//
                    // mTvInputSource.getMhlPortNum()
                    // mUiSourceList.add("HDMI "
                    // + (record.getInternalIdx() + 1) + " / MHL");
                    // } else {
                    mUiSourceList.add("HDMI " + (record.getInternalIdx() + 1));
                    // }
                    if (record.getInternalIdx() + 1 == 1) {
                        sourceMap.put("HDMI 1", Contants.HDMI1Uri);
                    } else if (record.getInternalIdx() + 1 == 2) {
                        sourceMap.put("HDMI 2", Contants.HDMI2Uri);
                    } else if (record.getInternalIdx() + 1 == 3) {
                        sourceMap.put("HDMI 3", Contants.HDMI3Uri);
                    } else if (record.getInternalIdx() + 1 == 4) {
                        sourceMap.put("HDMI 4", Contants.HDMI4Uri);
                    }
                } else if (sourceTypeName.equalsIgnoreCase("RESERVED")) {
                    mUiSourceList.add("RESERVED");
                } else if (sourceTypeName.equalsIgnoreCase("SCART")) {
                    mUiSourceList.add("SCART");
                } else if (sourceTypeName.equalsIgnoreCase("SVIDEO")) {
                    mUiSourceList.add("SVIDEO");
                }
            }
        }
    }

    public void changeSourceByBroadcast(Context context, String str, int tunerType) {
        //check setupwizard is exist
        boolean factoryActive = false;
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                .getRunningTasks(100);
//        for (ActivityManager.RunningTaskInfo running : appList) {
//            Log.v("tv",
//                    "factory1 =" + running.baseActivity.getClassName());
//            Log.v("tv",
//                    "factory2 =" + running.topActivity.getClassName());
//            if (running.topActivity.getClassName().contains("com.google.android.tungsten.setupwraith")
//                    ||running.topActivity.getClassName().contains("com.mediatek.wwtv.setupwizard")) {
//                factoryActive = true;
//                break;
//            }
//
//        }

        //check 1st activity is enough
           Log.v("tv",
                    "factory1 =" + appList.get(0).baseActivity.getClassName());
            Log.v("tv",
                    "factory2 =" + appList.get(0).topActivity.getClassName());
            if(appList.get(0).topActivity.getClassName().contains("com.google.android.tungsten.setupwraith")
            ||appList.get(0).topActivity.getClassName().contains("com.mediatek.wwtv.setupwizard")){
                factoryActive = true;
            }

        if(!factoryActive) {
            ActivityManager mActivityManager2 = (ActivityManager) context
                    .getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> appList2 = mActivityManager2
                    .getRunningTasks(100);
            for (ActivityManager.RunningTaskInfo running :
                    appList2) {
                Log.v("tv", "factory2 =" +
                        running.topActivity.getClassName());
                if
                ("com.mediatek.wwtv.tvcenter.nav.TurnkeyUiMainActivity"
                        .equals(running.topActivity.getClassName())) {
                    break;
                } 
                else if(REGION_JP == MarketRegionInfo.getCurrentMarketRegion()){
                    Log.d("gzx", "  ISDB61 without response 'com. mediatek. wwtv. tvcenter. nav. TurnkeyUiMainActivity'");
                }
                else {
                   Intent mIntent = new Intent();
                    mIntent.setComponent(new ComponentName(
                            "com.mediatek.wwtv.tvcenter",
                            "com.mediatek.wwtv.tvcenter.nav.TurnkeyUiMainActivity"));
                    mIntent.setData(Uri.parse(sourceMap.get(str)));
                    mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(mIntent);
                }

            }

            if (sourceMap.containsKey(str)) {
                if (REGION_JP == MarketRegionInfo.getCurrentMarketRegion()){
                    Intent tmp = new Intent("com.mediatek.tv.action.SELECT_SOURCE");
                    tmp.setClassName("com.mediatek.wwtv.tvcenter","com.mediatek.wwtv.tvcenter.nav.TurnkeyUiMainActivity");
                    tmp.putExtra("com.mediatek.select.sourcename", str);
                    tmp.putExtra("com.mediatek.select.tunertype",tunerType);
                    tmp.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(tmp);
                }else{
                    Intent tmp = new Intent(Intent.ACTION_VIEW);
                    tmp.setAction("com.mediatek.select.source");
                    tmp.putExtra("com.mediatek.select.sourcename", str);
                    tmp.putExtra("com.mediatek.select.tunertype",tunerType);
                    context.sendBroadcast(tmp);
                }
		mHandler.removeMessages(MESSAGE_UPDATE_STATE);
		Message message = mHandler.obtainMessage();
		message.what = MESSAGE_UPDATE_STATE;
		message.obj = context;
		Bundle bundle = new Bundle();    
		bundle.putString("keyret","SOURCE");   
		bundle.putInt("color",COLOR_GREEN);   
		message.setData(bundle);
		mHandler.sendMessageDelayed(message, 3000);

		updateStateService(context, 0, str, COLOR_WHITE);
                
                showToast(str);
            } else {
                showToast(context.getString(R.string.factory_reciver_source_null)
                        + " " + str);

            }
        }
    }

    @SuppressLint("ShowToast")
    public void showToast(String str) {
        mToast.setText(str);

        mToast.show();
    }

    public void cancelToast() {
        if (mToast != null)
            mToast.cancel();
    }

    public boolean isCurSourceIsTv() {
        Log.d(TAG, "CurSource:"
                + MtkTvInputSource.getInstance().getCurrentInputSourceName());
        if (MtkTvInputSource.getInstance().getCurrentInputSourceName()
                .equals("DTV")
                || MtkTvInputSource.getInstance().getCurrentInputSourceName()
                .equals("ATV")
                ||MtkTvInputSource.getInstance().getCurrentInputSourceName()
                .equals("TV")) {
            return true;
        } else {
            return false;
        }

    }

    public boolean isCurSourceIsDtv(){
        Log.d(TAG, "CurSource:"
                + MtkTvInputSource.getInstance().getCurrentInputSourceName());
        if (MtkTvInputSource.getInstance().getCurrentInputSourceName()
                .equals("DTV")){
            return true;
        } else {
            return false;
        }
    }

    public static boolean isFactoryMMode(Context context) {
        boolean mode = false;
        String str = null;

        str = MtkTvFApiInformation.getInstance().getIniParameter(
                Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE);

        /*
         * try { str = Settings.System.getInt(context.getContentResolver(),
         * Contants.FACTORY_M_MODE_GO) == 1 ? "1" : "0"; } catch
         * (SettingNotFoundException e) { // TODO Auto-generated catch block str
         * = "0"; }
         */
        Log.d(TAG, str);
        if (str != null) {
            mode = str.equalsIgnoreCase("1") ? true : false;
        } else {
            mode = false;
        }

        /*if (mode) {
            Settings.System.putInt(context.getContentResolver(), Contants.FACTORY_M_MODE_GO, 1);
        }*/

        return mode;
    }
    private boolean isHDMIEnableByIndex(Context context,int index) {
        boolean mode = false;
        String str = null;
        String key = "";
        switch (index){
            case 1:
                key=Contants.FACTORY_HDMI1_ENABLE;
                break;
            case 2:
                key=Contants.FACTORY_HDMI2_ENABLE;
                break;
            case 3:
                key=Contants.FACTORY_HDMI3_ENABLE;
                break;
            case 4:
                key=Contants.FACTORY_HDMI4_ENABLE;
                break;

        }
        str = MtkTvFApiInformation.getInstance().getIniParameter(
                Contants.PATH_INPUT_SOURCE, key);
        Log.d(TAG, str);
        if (str != null) {
            mode = str.equalsIgnoreCase("1") ? true : false;
        } else {
            mode = false;
        }
        return mode;
    }

    private boolean isFirstUpdateKey(final FactorySetting factorySetting) {
        boolean mode = false;
        if (factorySetting.findUsbDir()) {
            File file = factorySetting
                    .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR);
            mode = file.exists();
        }
        return mode;
    }

	private boolean isAutoTestStart(){
		boolean isStarted = false;
		File retFile = new File("/vendor/tvcertificate/TestResult.ini");
		if(retFile.exists()){
			String ret = MtkTvFApiInformation.getInstance().getIniParameter(retFile.getAbsolutePath(), "Result:Checked");
			if(ret != null && ret.equals("0")){
				isStarted = true;
			}
		}
		return isStarted;
	}

    private boolean isPanelDirExists(final FactorySetting factorySetting) {
        boolean mode = false;
        if (factorySetting.findUsbDir()) {
            File file = factorySetting
                    .getFile(Contants.FACTORY_PAGE2_PANEL_UPDATE_PATH);
            mode = file.exists();
        }
        return mode;
    }

    private boolean isChannelDirExists(final FactorySetting factorySetting) {
        boolean mode = false;
        if (factorySetting.findUsbDir()) {
            File file = factorySetting.getFile(Contants.PATH_CHANNEL);
            mode = file.exists();
        }
        return mode;
    }

    private void copySpecialKeyFile(final FactorySetting factorySetting) {
        if (factorySetting.findUsbDir()) {
            File file = factorySetting
                    .getFile(Contants.KEY_PATH_STRING_UPDATE_DIR
                            + "/specialkey.ini");
            if (file.exists()) {
                MtkTvFApiSystem.getInstance().copyFile(file.getAbsolutePath(),
                        Contants.PATH_KEYINI, false);
            }
        }

    }

    public static boolean setFactoryMMode(Context context, int mode) {
        boolean isSucces = false;
        isSucces = (MtkTvFApiInformation.getInstance().setIniParameter(
                Contants.PATH_FACTORYINI, Contants.FACTORY_M_MODE, "" + mode) == -1) ? false
                : true;
        if(mode==0) {
            //MtkTvFApiSystem.getInstance().setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_SECONDARY);
            FactorySetting.getInstance(context).factoryResetPowerMode();
            //set skip wizard = 0
            isSucces=(MtkTvFApiInformation.getInstance().setIniParameter(
                    Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_SKIP_WIZARDSETUP, "" + mode) == -1) ? false
                    : true;
	    //turn off keypadTest
            MtkTvUtil.KeypadControl(0);
        }
        else{
            MtkTvFApiSystem.getInstance().setFactoryPowerMode(MtkTvFApiSystemTypes.EnumSystemFactoryPowerMode.E_MTK_FAPI_SYSTEM_FACTORY_POWER_MODE_DIRECT);
            //set skip wizard =1
            isSucces=(MtkTvFApiInformation.getInstance().setIniParameter(
                    Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_SKIP_WIZARDSETUP, "" + mode) == -1) ? false
                    : true;
            //set auto backlight off
            int picMode=Settings.Global.getInt(context.getContentResolver(), "picture_mode",0);
            Settings.Global.putInt(context.getContentResolver(), getBlackLightName(picMode),0);

            //set backlight & dreamTime
            int backlightInt=1;
            int dreamTimeInt=1;
            int twoHourInt=7200000;
            try{
                backlightInt = Settings.Global.getInt(context.getContentResolver(), "picture_backlight");
                dreamTimeInt=Settings.System.getInt(context.getContentResolver(), SCREEN_OFF_TIMEOUT);
            }catch (Settings.SettingNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(backlightInt!=100||dreamTimeInt!=twoHourInt){
                Settings.Global.putInt(context.getContentResolver(), "picture_backlight", 100);
                Settings.System.putInt(context.getContentResolver(), SCREEN_OFF_TIMEOUT, twoHourInt);
            }
        }
        Settings.System.putInt(context.getContentResolver(), Contants.FACTORY_M_MODE_GO, mode);

        return isSucces;
    }

    private boolean setFirstUpdateKey(Context context, int mode) {
        boolean isSucces = false;
        /*
         * isSucces = (MtkTvFApiInformation.getInstance()
         * .setIniParameter(Contants.PATH_KEYINI,Contants.FACTORY_FIRSTUPKEY,
         * ""+mode) == -1) ? false : true;
         */
        /*
         * isSucces = Settings.System.putInt(context.getContentResolver(),
         * Contants.FACTORY_FIRSTUPKEY_GO, mode);
         */
        return isSucces;
    }

    private boolean setMacBarShow(Context context, int mode) {
        boolean isSucces = false;
        isSucces = Settings.Global.putInt(context.getContentResolver(),
                Contants.FACORY_MACBARCODE_SHOW, mode);
        return isSucces;
    }

    private boolean getMacBarShow(Context context) {
        boolean isSucces = false;
        try {
            if (Settings.Global.getInt(context.getContentResolver(),
                    Contants.FACORY_MACBARCODE_SHOW) == 1)
                isSucces = true;
            else
                isSucces = false;
        } catch (SettingNotFoundException e) {
            // TODO Auto-generated catch block
            isSucces = false;
        }
        return isSucces;
    }

    public String getCurSource() {
        return MtkTvInputSource.getInstance().getCurrentInputSourceName();
    }

    @SuppressLint("NewApi")
    private void broadcastIntentOut(Context context, String broadcastType) {
        try {
            synchronized (FactoryKeyReciver.class) {
                Intent intent = new Intent();

                intent.setAction(broadcastType);
                context.sendBroadcastAsUser(intent,
                        UserHandle.getUserHandleForUid(1000));
                Log.d(TAG, "broadcastIntentOut==>do broadcast broadcastType="
                        + broadcastType);
            }
        } catch (Exception e) {
            Log.d(TAG, "RemoteException:" + e.getMessage());
        }
    }

    private boolean isInStartPage(Context context){
        boolean factoryActive = false;
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                .getRunningTasks(100);
//        for (ActivityManager.RunningTaskInfo running : appList) {
//            Log.v("tv",
//                    "factory1 =" + running.baseActivity.getClassName());
//            Log.v("tv",
//                    "factory2 =" + running.topActivity.getClassName());
//            if (running.topActivity.getClassName().contains("com.google.android.tungsten.setupwraith")
//                    ||running.topActivity.getClassName().contains("com.mediatek.wwtv.setupwizard")) {
//                factoryActive = true;
//                break;
//            }
//
//        }

        //check 1st activity is enough
        Log.v("tv",
                "factory1 =" + appList.get(0).baseActivity.getClassName());
        Log.v("tv",
                "factory2 =" + appList.get(0).topActivity.getClassName());
        if(appList.get(0).topActivity.getClassName().contains("com.google.android.tungsten.setupwraith")
                ||appList.get(0).topActivity.getClassName().contains("com.mediatek.wwtv.setupwizard")){
            factoryActive = true;
        }

        return factoryActive;
    }

    private boolean checkMacAndDeviceID(FactorySetting factorySetting) {
    	boolean resultMac = true;
    	boolean resultDevcieId = true;
			if (!factorySetting.isMacExist()) {
				resultMac = false;
				if (!factorySetting.getMACFromIni().equalsIgnoreCase("NG")
						&&factorySetting.getMACFromIni().length()>0){
					Log.i(TAG, "checkMacAndDeviceID setMAC from ini");
					resultMac = factorySetting.setMAC(factorySetting.getMACFromIni());
				}
			}
			
			if (!factorySetting.isDeviceIdExist()) {
				resultDevcieId = false;
				if (!factorySetting.getDeviceIDFormIni().equalsIgnoreCase("NG")
						&&factorySetting.getDeviceIDFormIni().length()>0){
					Log.i(TAG, "checkMacAndDeviceID setDeviceID from ini");
					resultDevcieId = factorySetting.setDeviceID(factorySetting.getDeviceIDFormIni());
				}
			}
    	return resultMac&&resultDevcieId;
    }
	
	private void sendKeyCode(){
		new Thread() {
                         public void run() {
                                try {
                                    Instrumentation inst = new Instrumentation();
                                    inst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);
									//inst.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_POWER));
                                } catch (Exception e) {
                                }
                            }
                        }.start();
	}
         
	public boolean isServiceWork(Context mContext, String serviceName) { 
                if(isServiceWorked == false){
		ActivityManager myAM = (ActivityManager) mContext 
			.getSystemService(Context.ACTIVITY_SERVICE); 
		List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40); 
		if (myList.size() <= 0) { 
			return false; 
		} 
		for (int i = 0; i < myList.size(); i++) { 
			String mName = myList.get(i).service.getClassName().toString(); 
			if (mName.equals(serviceName)) { 
				isServiceWorked = true; 
				break; 
			} 
		} 
                }
		return isServiceWorked; 
	} 
        
	private void updateStateService(Context context, int type, String text, int color){

		Intent intent = new Intent();
		if(type == 0){
			intent.setAction("com.homwee.stateservice.setstate");
		} else if(type == 1){
			intent.setAction("com.homwee.stateservice.setkey");
		}
		intent.putExtra("text", text);
		intent.putExtra("color",color);
		context.sendBroadcast(intent);
		return;
	}
        
        private String getCurrentAnt(){
                int curAntMode = MtkTvConfig.getInstance().getConfigValue(MtkTvConfigType.CFG_BS_BS_SRC);
                if(curAntMode == 0){
                   return "AIR";
                } else if(curAntMode == 1){
                   return "CABLE";
                } else if(curAntMode == 2){
                   return "SATELLITE";
                }
                return "NULL";
        }

	private boolean isWifiEnable(Context context){
		WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		List<ScanResult> scanWifiList = wifiManager.getScanResults();
		if(scanWifiList != null && scanWifiList.size() > 0){
			return true;
		} else {
			return false;
		}
	}
     
        private boolean isBTEnable(Context context){
		BluetoothAdapter blueadapter=BluetoothAdapter.getDefaultAdapter();
		if(blueadapter != null && blueadapter.isEnabled()){
			return true;
		} else {
			return false;
		}
        }

	private boolean isAllKeyExist(FactorySetting factorySetting){
		boolean isAllKeyExist = false;

		boolean isWidevineKeyExist = factorySetting.isWidevineKeyExist();

		boolean isHDCPKey1XExist = factorySetting.isHDCPKey1XExist();

		boolean isHDCPKey2XExist = factorySetting.isHDCPKey2XExist();

		boolean isDTVCIPlusKeyExist = factorySetting.isDTVCIPlusKeyExist();

		boolean isESNKeyExist = factorySetting.isNETFLIXKeyExist();

		boolean isKeyMasterExist = factorySetting.isKeyMasterExist();

		boolean	isPlayReadyKeyExist = factorySetting.isPlayReadyKeyExist();


		boolean	isHashKeyExist = factorySetting.isHashKeyExist();

		boolean	isMacExist = factorySetting.isMacExist();

		boolean	isDeviceIdExist = factorySetting.isDeviceIdExist();

		boolean isCLIENTCAkeyExist = factorySetting.isCLIENTCAKeyExist();

		isAllKeyExist = isMacExist && isDeviceIdExist && isHDCPKey1XExist
			&& isWidevineKeyExist && isKeyMasterExist
			&& isPlayReadyKeyExist && isHashKeyExist;
		if(factorySetting.isHdcp2xKeyNeeded()){
			isAllKeyExist=isAllKeyExist&&isHDCPKey2XExist;
		}
		if(factorySetting.isHdcp2xKeyNeeded()) {
			isAllKeyExist = isAllKeyExist && isESNKeyExist;
		}
		if(factorySetting.isCIKeyNeeded()){
			isAllKeyExist=isAllKeyExist&&isDTVCIPlusKeyExist;
		}
        if(factorySetting.isPlayReadyKey25Needed()){
            isAllKeyExist=isAllKeyExist  && isCLIENTCAkeyExist; //&& isPlayReady25KeyExist
        }
                return isAllKeyExist;
	}

	 /**
     * clear application data
     */
    /*public static void clearApplicationData(String pkgName) {
		Log.i(TAG,"pkgName: " + pkgName);
        if (TextUtils.isEmpty(pkgName)) {
            return;
        }
        // PackageDataObserver packageDataObserver = new PackageDataObserver();
        PackageManager packageManager = BaseApplication.getContext().getPackageManager();
        packageManager.clearApplicationUserData(pkgName, null);
    }*/

    public static void clearApplications(Context context) {
        String[] pkgNames = new String[]{"com.google.android.tvlauncher", "com.google.android.tv.remote.service", ""};
        for (String pkgName : pkgNames){
			Log.i(TAG,"pkgName: " + pkgName);
			if (TextUtils.isEmpty(pkgName)) {
            return;
        }
        // PackageDataObserver packageDataObserver = new PackageDataObserver();
		ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
		String activityName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
		Log.i(TAG," activityName= " + activityName);
		//com.android.tv.settings.MainSettings
		//com.google.android.tvlauncher.MainActivity
        PackageManager packageManager = context.getPackageManager();
        packageManager.clearApplicationUserData(pkgName, null);

        }
    }

	 public static void clearTvRemoteDate(Context context) {
        String[] pkgNames = new String[]{"com.google.android.tv.remote.service", ""};
        for (String pkgName : pkgNames){
			Log.i(TAG,"pkgName: " + pkgName);
			if (TextUtils.isEmpty(pkgName)) {
            return;
        }
        // PackageDataObserver packageDataObserver = new PackageDataObserver();
		ActivityManager mActivityManager = (ActivityManager) context
                            .getSystemService(Context.ACTIVITY_SERVICE);
		String activityName = mActivityManager.getRunningTasks(1).get(0).topActivity.getClassName();
		Log.i(TAG," activityName= " + activityName);
		//com.android.tv.settings.MainSettings
		//com.google.android.tvlauncher.MainActivity
         PackageManager packageManager = context.getPackageManager();
         packageManager.clearApplicationUserData(pkgName, null);
	   Log.i(TAG,"clearTvRemoteDate --  android.tv.remote.service  clearApplicationUserData");
        }
    }

    private void initDataPath(Context context,FactorySetting factorySetting){
		Log.d("zcj","Start initDataPath");
		String platform=SystemProperties.get("ro.board.platform", "");
        Map<String, Object> mDataIndex = FactoryIniReadService.readIni(factorySetting.getDataIndex());
//        for(String key:mDataIndex.keySet()){
//            Map<String,String> data =(Map<String, String>)mDataIndex.get(key);
//            Log.d("zcj",key);
//            for(String k:data.keySet()){
//                Log.d("zcj",data.get(k));
//            }
//        }
        if(mDataIndex==null||mDataIndex.size()==0){
            Log.d(TAG,"mDataIndex is Null ,Path="+factorySetting.getDataIndex());
        }else {
            Contants.PATH_FACTORYINI = ((Map<String, String>) mDataIndex.get("Factory")).get("m_pFactoryRecord_File");
            Contants.PATH_CUSTOM_FUNC_INI = ((Map<String, String>) mDataIndex.get("Misc")).get("m_pCustomizationFunc_File");
            Contants.PATH_PROJECT_INFO = ((Map<String, String>) mDataIndex.get("model")).get("m_pModeInfo_File");
            Contants.PATH_INPUT_SOURCE = ((Map<String, String>) mDataIndex.get("InputSource")).get("m_pInputSourceConfig_File");
            Contants.PATH_IR_CONFIG = ((Map<String, String>) mDataIndex.get("ir")).get("m_pIrConfig_File");
            Contants.FACTORY_PAGE2_PQ_PATH = ((Map<String, String>) mDataIndex.get("panel")).get("PQBinPathName");
            String FACTORY_PAGE2_PQGENERAL_COLOR = ((Map<String, String>) mDataIndex.get("PQ_general")).get("m_pIniColorTuner_File");
            Contants.FACTORY_PAGE2_PQGENERAL_PATH = FACTORY_PAGE2_PQGENERAL_COLOR.substring(0, FACTORY_PAGE2_PQGENERAL_COLOR.lastIndexOf("/") + 1);
            Contants.FACTORY_PAGE2_AQ_PATH = ((Map<String, String>) mDataIndex.get("AQ")).get("AQPathName");
            Contants.FACTORY_PAGE2_COLORMA_PATH = ((Map<String, String>) mDataIndex.get("ColorMatrix")).get("MatrixName");
            Contants.FACTORY_PAGE2_COLORMA_PATH = Contants.FACTORY_PAGE2_COLORMA_PATH.substring(0,Contants.FACTORY_PAGE2_COLORMA_PATH.lastIndexOf("/")+1);
            Contants.FACTORY_PAGE2_PANEL_INI_PATH = ((Map<String, String>) mDataIndex.get("panel")).get("m_pPanelName");
            Contants.FACTORY_PAGE2_PANEL_PATH = Contants.FACTORY_PAGE2_PANEL_INI_PATH.substring(0, Contants.FACTORY_PAGE2_PANEL_INI_PATH.lastIndexOf("/") + 1);
            String FACTORY_PAGE2_MODEL_PATH_CUSTOMER1INI=((Map<String, String>) mDataIndex.get("model")).get("m_customerIniFile");
            Contants.FACTORY_PAGE2_MODEL_PATH = FACTORY_PAGE2_MODEL_PATH_CUSTOMER1INI.substring(0,FACTORY_PAGE2_MODEL_PATH_CUSTOMER1INI.lastIndexOf("/")+1);
            Contants.FACTORY_PAGE2_EDIDBIN_PATH = ((Map<String, String>) mDataIndex.get("EDID")).get("m_pEdidBinPath");
            Contants.FACTORY_PAGE2_HDRBIN_INI_PATH = ((Map<String, String>) mDataIndex.get("Hdr")).get("m_pIniFile");
            Contants.FACTORY_PAGE2_HDRBIN_PATH = Contants.FACTORY_PAGE2_HDRBIN_INI_PATH.substring(0, Contants.FACTORY_PAGE2_HDRBIN_INI_PATH.lastIndexOf("/"));
            Contants.FACTORY_PAGE2_MODULE_NAME_PATH = ((Map<String, String>) mDataIndex.get("module")).get("m_pModuleName");
            Contants.FACTORY_PAGE2_MODULE_PATH = Contants.FACTORY_PAGE2_MODULE_NAME_PATH.substring(0, Contants.FACTORY_PAGE2_MODULE_NAME_PATH.lastIndexOf("/") + 1);
            Contants.FACTORY_PAGE2_CUSTOMER_PATH = ((Map<String, String>) mDataIndex.get("model")).get("m_customerIniFile");
            Contants.FACTORY_PAGE1_AQ_VERSION_PATH = Contants.FACTORY_PAGE2_AQ_PATH + "AQ_Version.ini";
            Contants.FACTORY_EXTRA_BOARD_PATH = ((Map<String, String>) mDataIndex.get("board")).get("m_pBoardName");
            //for tvtools export
            if(platform.equals("m5621") || platform.equals("m7322")) {
            	Contants.FACTORY_TVTOOLS_INPUTSOURCEPATH = "/vendor/tvconfig/config/aq/";
	            Contants.FACTORY_TVTOOLS_SOUNDSTYLEPATH = "/vendor/tvconfig/config/aq/";
	            Contants.FACTORY_TVTOOLS_OSDMAPPINGPATH = "/vendor/tvconfig/config/PQ_general/OsdMapping.ini";
	            Contants.FACTORY_TVTOOLS_NLAPATH = "/vendor/tvconfig/config/PQ_general/NLA.ini";
	            Contants.FACTORY_TVTOOLS_OVERSCANPATH = "/vendor/tvconfig/apollo/overscan.ini";
            }else {
	            Contants.FACTORY_TVTOOLS_INPUTSOURCEPATH = ((Map<String, String>) mDataIndex.get("AQ")).get("AqInputSrcPathName");
	            Contants.FACTORY_TVTOOLS_SOUNDSTYLEPATH = ((Map<String, String>) mDataIndex.get("AQ")).get("AqSoundStylePathName");
	            Contants.FACTORY_TVTOOLS_OSDMAPPINGPATH = ((Map<String, String>) mDataIndex.get("PQ_general")).get("m_pIniOsdMapping_File");
	            Contants.FACTORY_TVTOOLS_NLAPATH = ((Map<String, String>) mDataIndex.get("PQ_general")).get("m_pIniNLA_File");
	            Contants.FACTORY_TVTOOLS_OVERSCANPATH = ((Map<String, String>) mDataIndex.get("Overscan")).get("m_pOverscan_File");
            }
            
            if(mDataIndex.containsKey("CustomerDataVersion")) {
                Contants.FACTORY_DATAINDEX_DATAVERSION = ((Map<String, String>) mDataIndex.get("CustomerDataVersion")).get("m_DataVersion");
            }
            if(((Map<String,String>) mDataIndex.get("panel")).containsKey("HSYPQBinPathName")) {
                Contants.FACTORY_PAGE1_HSYPQBIN_PATH = ((Map<String, String>) mDataIndex.get("panel")).get("HSYPQBinPathName");
            }
            Contants.FACTORY_BOOTLOGOCFG_FILE=((Map<String, String>) mDataIndex.get("BootLogoMusic")).get("m_pBootLogoMusicCfg_File");
            if(((Map<String,String>) mDataIndex.get("Factory")).containsKey("m_pAutoEnterFactory_File")) {
                Contants.PATH_FACTORY_AUTOENTERFACTORY_INI = ((Map<String, String>) mDataIndex.get("Factory")).get("m_pAutoEnterFactory_File");
            }
            if(((Map<String,String>) mDataIndex.get("TCON_BIN")).containsKey("m_pIniTconCfgFile")) {
                Contants.FACTORY_TCONCFGFILE = ((Map<String, String>) mDataIndex.get("TCON_BIN")).get("m_pIniTconCfgFile");
            }
			
			try {
				Contants.FACTORY_DATAINDEX_HASHKEY_SELECT = ((Map<String, String>) mDataIndex.get("CustomerDataVersion")).get("m_hashkeySelect");
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
    }
    public String readKeyFromEEPROM(EnumEepromKey keyType){

        String hardware=Build.HARDWARE;
        Log.d(TAG, "KEY_EEPROM_PATH:"+KEY_EEPROM_PATH);

        int[] keyStartAddress= new int[EnumEepromKey.values().length];
        int[] keyEndAddress= new int[EnumEepromKey.values().length];
        String[] keyNames=new String[EnumEepromKey.values().length];
        int actual = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_FAIL;
        int expected = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK;
        int ret = MtkTvFApiResultTypeBase.MTKTV_FAPI_RET_OK;
        keyNames[EnumEepromKey.E_EepromKey_HDCP14.ordinal()] = "HDCP14";
        keyNames[EnumEepromKey.E_EepromKey_HDCP2.ordinal()] = "HDCP2";
        keyNames[EnumEepromKey.E_EepromKey_MAC.ordinal()] = "MAC";
        keyNames[EnumEepromKey.E_EepromKey_WIDEVINE.ordinal()] = "WIDEVINE";
        keyNames[EnumEepromKey.E_EepromKey_PLAYREADY30_BGROUPCERT.ordinal()] = "PLAYREADY30_BGROUPCERT";
        keyNames[EnumEepromKey.E_EepromKey_PLAYREADY30_ZGPRIV.ordinal()] = "PLAYREADY30_ZGPRIV";
        //keyNames[EnumEepromKey.E_EepromKey_KEYMASTER.ordinal()]                               = "KEYMASTER"
        keyNames[EnumEepromKey.E_EepromKey_DEVICE_ID.ordinal()] = "DEVICE_ID";
        keyNames[EnumEepromKey.E_EepromKey_NETFLIX50_KPEKPH.ordinal()] = "NETFLIX50_KPEKPH";
        keyNames[EnumEepromKey.E_EepromKey_NETFLIX50_ESNID.ordinal()] = "NETFLIX50_ESNID";
        keyNames[EnumEepromKey.E_EepromKey_HASHKEY.ordinal()] = "HASH_KEY";
        keyNames[EnumEepromKey.E_EepromKey_PROJECT_ID.ordinal()] = "PROJECT_ID";
        keyNames[EnumEepromKey.E_EepromKey_MMODE.ordinal()] = "MMODE";
        keyNames[EnumEepromKey.E_EepromKey_AGINGMODE.ordinal()] = "AGINGMODE";
        keyNames[EnumEepromKey.E_EepromKey_CIPLUS.ordinal()]="CIPLUS";

        for (EnumEepromKey Type : EnumEepromKey.values()) {
            String startAddressKey = "EEPROM_KEY_SETTING:" + keyNames[Type.ordinal()] + "_START_ADDRESS";
            String endAddressKey = "EEPROM_KEY_SETTING:" + keyNames[Type.ordinal()] + "_END_ADDRESS";

            String startAddressStrData = MtkTvFApiInformationWrapper.getInstance().getIniParameter(KEY_EEPROM_PATH, startAddressKey);
            String endAddressStrData = MtkTvFApiInformationWrapper.getInstance().getIniParameter(KEY_EEPROM_PATH, endAddressKey);

            Log.d(TAG, startAddressKey + "=" + startAddressStrData + ", " + endAddressKey + "=" + endAddressStrData);
            if ((!startAddressStrData.equals("")) && (!endAddressStrData.equals(""))) {
                keyStartAddress[Type.ordinal()] = Integer.decode(startAddressStrData);
                keyEndAddress[Type.ordinal()] = Integer.decode(endAddressStrData);


            }
        }
        //IicDevice iicdevice =ProductFun.iicdevice;//
        IicDevice iicdevice=IicDevice.BOARD_I2C_DEVICE_9;
        int readPos = keyStartAddress[keyType.ordinal()];

        //Relative to EEPROM spec
        //ie:in this case, address is 0x0020. addr1: 0x00, addr2:0x20
        byte addr2 = (byte) (readPos & 0x00FF);
        byte addr1 = (byte) ((readPos & 0xFF00) >> 8);
        short size = (short) (keyEndAddress[keyType.ordinal()] - keyStartAddress[keyType.ordinal()] + 1);


        ArrayList<Byte> iicAddr = new ArrayList<Byte>();
        iicAddr.add(addr1);
        iicAddr.add(addr2);

        ArrayList<Byte> getBackData = new ArrayList<Byte>();

        {
            actual = MtkTvFApiPeripheral.getInstance().readFromIic(iicdevice, MtkTvFApiIicReadMode.E_MTK_FAPI_IIC_READ_MODE_DEFAULT, iicAddr, size, getBackData);
            ret |= actual;
        }
        //Log.d(TAG, "readFromIic size: " + getBackData.size());
        if (keyType == EnumEepromKey.E_EepromKey_MAC) {
            StringBuilder sb_mac = new StringBuilder();
            for (int i = 0; i < getBackData.size(); i++) {
                sb_mac.append(String.format("%02X%s", getBackData.get(i), (i < getBackData.size() - 1) ? ":" : ""));
            }
            Log.d(TAG, "Get the MAC address : " + sb_mac.toString());
            readMACString=sb_mac.toString();
        }

        if(keyType == EnumEepromKey.E_EepromKey_PROJECT_ID){
            StringBuilder sb_pid = new StringBuilder();
            for (int i = getBackData.size() -1; i >= 0; i--) {
                sb_pid.append(getBackData.get(i));
            }
            Log.d(TAG, "Get the pid : " + sb_pid.toString());
            readPid=sb_pid.toString();
        }

        int count1=0;
        int count2=0;
        for(int i=0;i<getBackData.size();i++){
            if(getBackData.get(i)==0){
                count1++;
            }else if(getBackData.get(i)==-1){
                count2++;
            }
        }
        if((count1 == getBackData.size())||(count2 == getBackData.size())){
            return "NG";
        }else{
            return "OK";
        }


    }

		
    private void BTCheck(Context mContext){
        mBtManager = BTManager.getInstance(mContext);
        mBluetoothAdapter = mBtManager.mBTAdapter;
        if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }

        mBtManager.setHandler(btHandler);
        mBtManager.registerBTReceiver();

        startSearch();

    }

    private void startSearch() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                if (mBluetoothAdapter != null) {
                    mBluetoothAdapter.startDiscovery();
                }
            }
        }).start();
    }

    public void getDeviceMac(Context context){
        String KEY_WIFI_MAC_ADDRESS="wifi_mac_address";
        SharedPreferences sharedPrefs = context.getSharedPreferences(PREFERENCES_WIFI_MAC_ADDRESS, Context.MODE_PRIVATE);
        SharedPreferences.Editor ed =sharedPrefs.edit();
        WifiManager mWifiManager = context.getSystemService(WifiManager.class);
        final String[] macAddresses = mWifiManager.getFactoryMacAddresses();
        String macAddress = null;
        if (macAddresses != null && macAddresses.length > 0) {
            macAddress = macAddresses[0];
        }

        if (TextUtils.isEmpty(macAddress)) {
            ed.putString(KEY_WIFI_MAC_ADDRESS," ");
        } else {
            macAddress=macAddress.toUpperCase();
            ed.putString(KEY_WIFI_MAC_ADDRESS, macAddress);
        }
        Log.d(TAG,"getDeviceMac : "+macAddress);
        ed.commit();
    }

    public boolean isLiveTVRunning(Context context) {
        boolean factoryActive = false;
        ActivityManager mActivityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> appList = mActivityManager
                .getRunningTasks(1);
        ActivityManager.RunningTaskInfo running = appList.get(0);
        Log.v(TAG, "factory2 =" + running.topActivity.getClassName());
        if (running.topActivity.getClassName().contains("com.mediatek.wwtv.tvcenter.nav.TurnkeyUiMainActivity")
                || running.topActivity.getClassName().contains("com.mediatek.wwtv.tvcenter")) {
            factoryActive = true;
        }
        return factoryActive;
    }
	
    public void presetHashkey(){
        Log.d(TAG,"start preset hashkey");
        String keystatusHashkeySel=MtkTvFApiInformation.getInstance().getIniParameter(
                Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_HASHKEY);
        keystatusHashkeySel=keystatusHashkeySel.substring(keystatusHashkeySel.indexOf("@")+1,keystatusHashkeySel.length());
        String dataindexHashkeySel=Contants.FACTORY_DATAINDEX_HASHKEY_SELECT;
        File hashFile = new File(Contants.KEY_PATH_HASH_KEY);
        if(!TextUtils.isEmpty(dataindexHashkeySel)){
            if(!dataindexHashkeySel.equalsIgnoreCase(keystatusHashkeySel) ||  !hashFile.exists()){
                String hashkeySel=MtkTvFApiInformation.getInstance().getIniParameter(
                        Contants.FACTOTY_HASHKEY_BACKUP_CFG, "HASHKEY:"+dataindexHashkeySel);
                String path=Contants.FACTOTY_HASHKEY_BACKUP_DIR+hashkeySel+"/"+"hashkey.sign";
                int copyRt = MtkTvFApiSystem.getInstance().copyFile(path,
                        Contants.KEY_PATH_HASH_KEY, false);
                Log.d(TAG,"preset hashkey,use: "+path+" ;and ret :"+copyRt);
                MtkTvFApiInformation.getInstance().setIniParameter(
                        Contants.KEYSTATUS_INI_FILEPATH, Contants.KEYSTATUS_HASHKEY,"PRESET@"+dataindexHashkeySel);
            }
        }
    }

    public static String getBlackLightName(int pictureMode){
        String autoBackName;
        switch (pictureMode){
            case 0:
                autoBackName="key_picture_mode_user_auto_backlight";
                break;
            case 2:
                autoBackName="key_picture_mode_sport_auto_backlight";
                break;
            case 3:
                autoBackName="key_picture_mode_vivid_auto_backlight";
                break;
            case 7:
                autoBackName="key_picture_mode_standard_auto_backlight";
                break;
            case 9:
                autoBackName="key_picture_mode_movie_auto_backlight";
                break;
            case 10:
                autoBackName="key_picture_mode_game_auto_backlight";
                break;
            case 11:
                autoBackName="key_picture_mode_energy_saving_auto_backlight";
                break;
            default:
                autoBackName="key_picture_mode_others_auto_backlight";
                break;
        }
        return autoBackName;
    }
}
